Aedis 1.4.1
A redis client library
cpp17_intro.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 <iostream>
8#include <boost/asio.hpp>
9#include <aedis.hpp>
10#include <aedis/src.hpp>
11
12namespace net = boost::asio;
13namespace resp3 = aedis::resp3;
15using aedis::adapt;
17
18void log(boost::system::error_code const& ec, char const* prefix)
19{
20 std::clog << prefix << ec.message() << std::endl;
21}
22
23auto main(int argc, char * argv[]) -> int
24{
25 try {
26 std::string host = "127.0.0.1";
27 std::string port = "6379";
28
29 if (argc == 3) {
30 host = argv[1];
31 port = argv[2];
32 }
33
34 // The request
36 req.push("HELLO", 3);
37 req.push("PING", "Hello world");
38 req.push("QUIT");
39
40 // The response.
41 std::tuple<aedis::ignore, std::string, aedis::ignore> resp;
42
43 net::io_context ioc;
44
45 // IO objects.
46 net::ip::tcp::resolver resv{ioc};
47 aedis::connection conn{ioc};
48
49 // Resolve endpoints.
50 net::ip::tcp::resolver::results_type endpoints;
51
52 // async_run callback.
53 auto on_run = [](auto ec)
54 {
55 if (ec)
56 return log(ec, "on_run: ");
57 };
58
59 // async_exec callback.
60 auto on_exec = [&](auto ec, auto)
61 {
62 if (ec) {
63 conn.cancel(operation::run);
64 return log(ec, "on_exec: ");
65 }
66
67 std::cout << "PING: " << std::get<1>(resp) << std::endl;
68 };
69
70 // Connect callback.
71 auto on_connect = [&](auto ec, auto)
72 {
73 if (ec)
74 return log(ec, "on_connect: ");
75
76 conn.async_run(on_run);
77 conn.async_exec(req, adapt(resp), on_exec);
78 };
79
80 // Resolve callback.
81 auto on_resolve = [&](auto ec, auto const& addrs)
82 {
83 if (ec)
84 return log(ec, "on_resolve: ");
85
86 endpoints = addrs;
87 net::async_connect(conn.next_layer(), endpoints, on_connect);
88 };
89
90 resv.async_resolve(host, port, on_resolve);
91
92 ioc.run();
93 return 0;
94
95 } catch (std::exception const& e) {
96 std::cerr << "Error: " << e.what() << std::endl;
97 }
98
99 return 1;
100}
101
A connection to the Redis server.
Definition: connection.hpp:32
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
operation
Connection operations that can be cancelled.
Definition: operation.hpp:18