Aedis 1.4.1
A redis client library
cpp20_subscriber.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 <boost/asio.hpp>
8#if defined(BOOST_ASIO_HAS_CO_AWAIT)
9#include <boost/asio/experimental/awaitable_operators.hpp>
10#include <aedis.hpp>
11
12#include "common/common.hpp"
13
14namespace net = boost::asio;
15namespace resp3 = aedis::resp3;
16using namespace net::experimental::awaitable_operators;
17using steady_timer = net::use_awaitable_t<>::as_default_on_t<net::steady_timer>;
18using aedis::adapt;
19
20/* This example will subscribe and read pushes indefinitely.
21 *
22 * To test send messages with redis-cli
23 *
24 * $ redis-cli -3
25 * 127.0.0.1:6379> PUBLISH channel some-message
26 * (integer) 3
27 * 127.0.0.1:6379>
28 *
29 * To test reconnection try, for example, to close all clients currently
30 * connected to the Redis instance
31 *
32 * $ redis-cli
33 * > CLIENT kill TYPE pubsub
34 */
35
36// Receives pushes.
37auto receiver(std::shared_ptr<connection> conn) -> net::awaitable<void>
38{
39 using resp_type = std::vector<resp3::node<std::string>>;
40 for (resp_type resp;;) {
41 co_await conn->async_receive(adapt(resp));
42 std::cout << resp.at(1).value << " " << resp.at(2).value << " " << resp.at(3).value << std::endl;
43 resp.clear();
44 }
45}
46
47auto co_main(std::string host, std::string port) -> net::awaitable<void>
48{
49 auto ex = co_await net::this_coro::executor;
50 auto conn = std::make_shared<connection>(ex);
51 steady_timer timer{ex};
52
54 req.push("HELLO", 3);
55 req.push("SUBSCRIBE", "channel");
56
57 // The loop will reconnect on connection lost. To exit type Ctrl-C twice.
58 for (;;) {
59 co_await connect(conn, host, port);
60 co_await ((conn->async_run() || healthy_checker(conn) || receiver(conn)) && conn->async_exec(req));
61
62 conn->reset_stream();
63 timer.expires_after(std::chrono::seconds{1});
64 co_await timer.async_wait();
65 }
66}
67
68#endif // defined(BOOST_ASIO_HAS_CO_AWAIT)
Creates Redis requests.
Definition: request.hpp:169
void push(std::string_view cmd, Ts const &... args)
Appends a new command to the end of the request.
Definition: request.hpp:261
auto adapt(std::size_t max_read_size=(std::numeric_limits< std::size_t >::max)()) noexcept
Creates an adapter that ignores responses.
Definition: adapt.hpp:199