1- /* Copyright (c) 2018-2022 Marcelo Zimbres Silva ([email protected] )1+ /* Copyright (c) 2018-2025 Marcelo Zimbres Silva ([email protected] )22 *
33 * Distributed under the Boost Software License, Version 1.0. (See
44 * accompanying file LICENSE.txt)
@@ -24,13 +24,25 @@ using boost::asio::awaitable;
2424using boost::asio::detached;
2525using boost::asio::consign;
2626
27+ template <class T >
28+ std::ostream& operator <<(std::ostream& os, std::optional<T> const & opt)
29+ {
30+ if (opt.has_value ())
31+ std::cout << opt.value ();
32+ else
33+ std::cout << " null" ;
34+
35+ return os;
36+ }
37+
2738void print (std::map<std::string, std::string> const & cont)
2839{
2940 for (auto const & e: cont)
3041 std::cout << e.first << " : " << e.second << " \n " ;
3142}
3243
33- void print (std::vector<int > const & cont)
44+ template <class T >
45+ void print (std::vector<T> const & cont)
3446{
3547 for (auto const & e: cont) std::cout << e << " " ;
3648 std::cout << " \n " ;
@@ -48,6 +60,7 @@ auto store(std::shared_ptr<connection> conn) -> awaitable<void>
4860 request req;
4961 req.push_range (" RPUSH" , " rpush-key" , vec);
5062 req.push_range (" HSET" , " hset-key" , map);
63+ req.push (" SET" , " key" , " value" );
5164
5265 co_await conn->async_exec (req, ignore);
5366}
@@ -67,6 +80,21 @@ auto hgetall(std::shared_ptr<connection> conn) -> awaitable<void>
6780 print (std::get<0 >(resp).value ());
6881}
6982
83+ auto mget (std::shared_ptr<connection> conn) -> awaitable<void>
84+ {
85+ // A request contains multiple commands.
86+ request req;
87+ req.push (" MGET" , " key" , " non-existing" );
88+
89+ // Responses as tuple elements.
90+ response<std::vector<std::optional<std::string>>> resp;
91+
92+ // Executes the request and reads the response.
93+ co_await conn->async_exec (req, resp);
94+
95+ print (std::get<0 >(resp).value ());
96+ }
97+
7098// Retrieves in a transaction.
7199auto transaction (std::shared_ptr<connection> conn) -> awaitable<void>
72100{
@@ -76,11 +104,15 @@ auto transaction(std::shared_ptr<connection> conn) -> awaitable<void>
76104 req.push (" HGETALL" , " hset-key" ); // Retrieves
77105 req.push (" EXEC" );
78106
107+ // TODO: Retrieve with MGET
79108 response<
80109 ignore_t , // multi
81110 ignore_t , // lrange
82111 ignore_t , // hgetall
83- response<std::optional<std::vector<int >>, std::optional<std::map<std::string, std::string>>> // exec
112+ response<
113+ std::optional<std::vector<int >>,
114+ std::optional<std::map<std::string, std::string>>
115+ > // exec
84116 > resp;
85117
86118 co_await conn->async_exec (req, resp);
@@ -98,6 +130,7 @@ awaitable<void> co_main(config cfg)
98130 co_await store (conn);
99131 co_await transaction (conn);
100132 co_await hgetall (conn);
133+ co_await mget (conn);
101134 conn->cancel ();
102135}
103136
0 commit comments