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
11#include <boost/asio/deferred.hpp>
12#include <boost/asio/detached.hpp>
13#include <boost/asio/use_future.hpp>
14
15#include <chrono>
16#include <thread>
17
18using namespace std::chrono_literals;
19
20namespace boost::redis {
21
22class sync_connection {
23public:
24 sync_connection()
25 : ioc_{1}
26 , conn_{std::make_shared<connection>(ioc_)}
27 { }
28
29 ~sync_connection() { thread_.join(); }
30
31 void run(config cfg)
32 {
33 // Starts a thread that will can io_context::run on which the
34 // connection will run.
35 thread_ = std::thread{[this, cfg]() {
36 conn_->async_run(cfg, asio::detached);
37 ioc_.run();
38 }};
39 }
40
41 void stop()
42 {
43 asio::dispatch(ioc_, [this]() {
44 conn_->cancel();
45 });
46 }
47
48 template <class Response>
49 auto exec(request const& req, Response& resp)
50 {
51 asio::dispatch(conn_->get_executor(), asio::deferred([this, &req, &resp]() {
52 return conn_->async_exec(req, resp, asio::deferred);
53 }))(asio::use_future)
54 .get();
55 }
56
57private:
58 asio::io_context ioc_{1};
59 std::shared_ptr<connection> conn_;
60 std::thread thread_;
61};
62
63} // namespace boost::redis
@ exec
Refers to connection::async_exec operations.
@ run
Refers to connection::async_run operations.