Boost.Redis: example/sync_connection.hpp Source File

Boost.Redis 1.84.0 A redis client library

Loading...
Searching...
No Matches
sync_connection.hpp
1
2/* Copyright (c) 2018-2024 Marcelo Zimbres Silva (mzimbres@gmail.com)
3 *
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE.txt)
6 */
7
8#include <boost/redis/connection.hpp>
9#include <boost/redis/request.hpp>
10#include <boost/asio/deferred.hpp>
11#include <boost/asio/detached.hpp>
12#include <boost/asio/use_future.hpp>
13#include <thread>
14#include <chrono>
15
16using namespace std::chrono_literals;
17
18namespace boost::redis
19{
20
21class sync_connection {
22public:
23 sync_connection()
24 : ioc_{1}
25 , conn_{std::make_shared<connection>(ioc_)}
26 { }
27
28 ~sync_connection()
29 {
30 thread_.join();
31 }
32
33 void run(config cfg)
34 {
35 // Starts a thread that will can io_context::run on which the
36 // connection will run.
37 thread_ = std::thread{[this, cfg]() {
38 conn_->async_run(cfg, {}, asio::detached);
39 ioc_.run();
40 }};
41 }
42
43 void stop()
44 {
45 asio::dispatch(ioc_, [this]() { conn_->cancel(); });
46 }
47
48 template <class Response>
49 auto exec(request const& req, Response& resp)
50 {
51 asio::dispatch(
52 conn_->get_executor(),
53 asio::deferred([this, &req, &resp]() { return conn_->async_exec(req, resp, asio::deferred); }))
54 (asio::use_future).get();
55 }
56
57private:
58 asio::io_context ioc_{1};
59 std::shared_ptr<connection> conn_;
60 std::thread thread_;
61};
62
63}
boost::redis::operation::exec
@ exec
Refers to connection::async_exec operations.
boost::redis::operation::run
@ run
Refers to connection::async_run operations.