Aedis 1.0.0  
High level Redis client
echo_server.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 <string>
8 #include <iostream>
9 #include <boost/asio.hpp>
10 #include <aedis.hpp>
11 
12 // Include this in no more than one .cpp file.
13 #include <aedis/src.hpp>
14 
15 namespace net = boost::asio;
16 using aedis::adapt;
18 using executor_type = net::io_context::executor_type;
19 using socket_type = net::basic_stream_socket<net::ip::tcp, executor_type>;
20 using tcp_socket = net::use_awaitable_t<executor_type>::as_default_on_t<socket_type>;
21 using acceptor_type = net::basic_socket_acceptor<net::ip::tcp, executor_type>;
22 using tcp_acceptor = net::use_awaitable_t<executor_type>::as_default_on_t<acceptor_type>;
23 using awaitable_type = net::awaitable<void, executor_type>;
25 
26 awaitable_type echo_loop(tcp_socket socket, std::shared_ptr<connection> db)
27 {
28  request req;
29  std::tuple<std::string> resp;
30 
31  for (std::string buffer;;) {
32  auto n = co_await net::async_read_until(socket, net::dynamic_buffer(buffer, 1024), "\n");
33  req.push("PING", buffer);
34  co_await db->async_exec(req, adapt(resp));
35  co_await net::async_write(socket, net::buffer(std::get<0>(resp)));
36  std::get<0>(resp).clear();
37  req.clear();
38  buffer.erase(0, n);
39  }
40 }
41 
42 awaitable_type listener()
43 {
44  auto ex = co_await net::this_coro::executor;
45  auto db = std::make_shared<connection>(ex);
46  db->async_run(net::detached);
47 
48  tcp_acceptor acc(ex, {net::ip::tcp::v4(), 55555});
49  for (;;)
50  net::co_spawn(ex, echo_loop(co_await acc.async_accept(), db), net::detached);
51 }
52 
53 int main()
54 {
55  try {
56  net::io_context ioc{BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO};
57  co_spawn(ioc, listener(), net::detached);
58  ioc.run();
59  } catch (std::exception const& e) {
60  std::cerr << e.what() << std::endl;
61  }
62 }
A high level connection to Redis.
Definition: connection.hpp:45
Creates Redis requests.
Definition: request.hpp:172
void clear()
Clears the request preserving allocated memory.
Definition: request.hpp:181
void push(boost::string_view cmd, Ts const &... args)
Appends a new command to the end of the request.
Definition: request.hpp:203
auto adapt() noexcept
Creates an adapter that ignores responses.
Definition: adapt.hpp:140