boost_redis 1.4.2
A redis client library
cpp20_resolve_with_sentinel.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/redis/connection.hpp>
8#include <boost/asio/use_awaitable.hpp>
9#include <boost/asio/redirect_error.hpp>
10#include <boost/asio/detached.hpp>
11#include <iostream>
12
13#if defined(BOOST_ASIO_HAS_CO_AWAIT)
14
15namespace net = boost::asio;
16using endpoints = net::ip::tcp::resolver::results_type;
23
24auto redir(boost::system::error_code& ec)
25 { return net::redirect_error(net::use_awaitable, ec); }
26
27// For more info see
28// - https://redis.io/docs/manual/sentinel.
29// - https://redis.io/docs/reference/sentinel-clients.
30auto resolve_master_address(std::vector<address> const& addresses) -> net::awaitable<address>
31{
32 request req;
33 req.push("SENTINEL", "get-master-addr-by-name", "mymaster");
34 req.push("QUIT");
35
36 auto conn = std::make_shared<connection>(co_await net::this_coro::executor);
37
38 response<std::optional<std::array<std::string, 2>>, ignore_t> resp;
39 for (auto addr : addresses) {
40 boost::system::error_code ec;
41 config cfg;
42 cfg.addr = addr;
43 // TODO: async_run and async_exec should be lauched in
44 // parallel here so we can wait for async_run completion
45 // before eventually calling it again.
46 conn->async_run(cfg, {}, net::consign(net::detached, conn));
47 co_await conn->async_exec(req, resp, redir(ec));
48 conn->cancel();
49 conn->reset_stream();
50 if (!ec && std::get<0>(resp))
51 co_return address{std::get<0>(resp).value().value().at(0), std::get<0>(resp).value().value().at(1)};
52 }
53
54 co_return address{};
55}
56
57auto co_main(config cfg) -> net::awaitable<void>
58{
59 // A list of sentinel addresses from which only one is responsive.
60 // This simulates sentinels that are down.
61 std::vector<address> const addresses
62 { address{"foo", "26379"}
63 , address{"bar", "26379"}
64 , cfg.addr
65 };
66
67 auto const ep = co_await resolve_master_address(addresses);
68
69 std::clog
70 << "Host: " << ep.host << "\n"
71 << "Port: " << ep.port << "\n"
72 << std::flush;
73}
74
75#endif // defined(BOOST_ASIO_HAS_CO_AWAIT)
A basic_connection that type erases the executor.
Definition: connection.hpp:308
Creates Redis requests.
Definition: request.hpp:46
std::decay_t< decltype(std::ignore)> ignore_t
Type used to ignore responses.
Definition: ignore.hpp:31
std::tuple< adapter::result< Ts >... > response
Response with compile-time size.
Definition: response.hpp:23
Address of a Redis server.
Definition: config.hpp:20
Configure parameters used by the connection classes.
Definition: config.hpp:30