Aedis 1.4.1
A redis client library
cpp17_intro_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 <iostream>
11#include <boost/asio.hpp>
12#include <aedis.hpp>
13
14// Include this in no more than one .cpp file.
15#include <aedis/src.hpp>
16
17namespace net = boost::asio;
18namespace resp3 = aedis::resp3;
19using aedis::adapt;
21
22template <class Adapter>
23auto exec(std::shared_ptr<connection> conn, resp3::request const& req, Adapter adapter)
24{
25 net::dispatch(
26 conn->get_executor(),
27 net::deferred([&]() { return conn->async_exec(req, adapter, net::deferred); }))
28 (net::use_future).get();
29}
30
31auto logger = [](auto const& ec)
32 { std::clog << "Run: " << ec.message() << std::endl; };
33
34auto main(int argc, char * argv[]) -> int
35{
36 try {
37 std::string host = "127.0.0.1";
38 std::string port = "6379";
39
40 if (argc == 3) {
41 host = argv[1];
42 port = argv[2];
43 }
44
45 net::io_context ioc{1};
46
47 auto conn = std::make_shared<connection>(ioc);
48
49 // Resolves the address
50 net::ip::tcp::resolver resv{ioc};
51 auto const res = resv.resolve(host, port);
52
53 // Connect to Redis
54 net::connect(conn->next_layer(), res);
55
56 // Starts a thread that will can io_context::run on which
57 // the connection will run.
58 std::thread t{[conn, &ioc]() {
59 conn->async_run(logger);
60 ioc.run();
61 }};
62
64 req.push("HELLO", 3);
65 req.push("PING");
66 req.push("QUIT");
67
68 std::tuple<aedis::ignore, std::string, aedis::ignore> resp;
69
70 // Executes commands synchronously.
71 exec(conn, req, adapt(resp));
72
73 std::cout << "Response: " << std::get<1>(resp) << std::endl;
74
75 t.join();
76 } catch (std::exception const& e) {
77 std::cerr << e.what() << std::endl;
78 }
79}
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
basic_connection< boost::asio::ip::tcp::socket > connection
A connection that uses a boost::asio::ip::tcp::socket.
Definition: connection.hpp:210
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