Aedis 1.0.0  
High level Redis client
subscriber_sync.cpp
1 /* Copyright (c) 2018-2022 Marcelo Zimbres Silva (mzimbres@gmail.com)
2  *
3  * Distributed under the Boost Software License, Version 1.0. (See
4  * accompanying file LICENSE.txt)
5  */
6 
7 #include <tuple>
8 #include <string>
9 #include <thread>
10 #include <boost/asio.hpp>
11 #include <aedis.hpp>
12 #include "print.hpp"
13 
14 // Include this in no more than one .cpp file.
15 #include <aedis/src.hpp>
16 
17 namespace net = boost::asio;
18 using aedis::adapt;
19 using aedis::resp3::node;
22 using event = connection::event;
23 
24 // See subscriber.cpp for more info about how to run this example.
25 
26 // Subscribe again everytime there is a disconnection.
27 void event_receiver(connection& conn)
28 {
29  request req;
30  req.push("SUBSCRIBE", "channel");
31 
32  for (;;) {
33  auto ev = conn.receive_event();
34  if (ev == connection::event::hello)
35  conn.exec(req);
36  }
37 }
38 
39 int main()
40 {
41  try {
42  net::io_context ioc{1};
43  auto work = net::make_work_guard(ioc);
44 
46  cfg.enable_events = true;
47  cfg.enable_reconnect = true;
48  connection conn{work.get_executor(), cfg};
49 
50  std::thread t1{[&]() { ioc.run(); }};
51  std::thread t2{[&]() { boost::system::error_code ec; conn.run(ec); }};
52  std::thread t3{[&]() { event_receiver(conn); }};
53 
54  for (std::vector<node<std::string>> resp;;) {
55  conn.receive_push(adapt(resp));
56  print_push(resp);
57  resp.clear();
58  }
59 
60  t1.join();
61  t2.join();
62  t3.join();
63 
64  } catch (std::exception const& e) {
65  std::cerr << e.what() << std::endl;
66  }
67 }
A high level connection to Redis.
Definition: connection.hpp:45
event
Events that are communicated by connection::async_receive_event.
Definition: connection.hpp:94
@ hello
Success sending AUTH and HELLO.
bool enable_events
Enable internal events, see connection::async_receive_event.
Definition: connection.hpp:87
bool enable_reconnect
Enable automatic reconnection (see also config::reconnect_interval).
Definition: connection.hpp:90
auto get_executor()
Returns the executor.
Definition: connection.hpp:151
Connection configuration parameters.
Definition: connection.hpp:55
Creates Redis requests.
Definition: request.hpp:172
void push(boost::string_view cmd, Ts const &... args)
Appends a new command to the end of the request.
Definition: request.hpp:203
A high level synchronous connection to Redis.
Definition: sync.hpp:24
auto adapt() noexcept
Creates an adapter that ignores responses.
Definition: adapt.hpp:140
A node in the response tree.
Definition: node.hpp:28