boost_redis 1.4.2
A redis client library
cpp20_json.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/deferred.hpp>
9#include <boost/asio/detached.hpp>
10#include <boost/describe.hpp>
11#include <boost/asio/consign.hpp>
12#include <boost/asio/use_awaitable.hpp>
13#include <string>
14#include <iostream>
15
16#if defined(BOOST_ASIO_HAS_CO_AWAIT)
17
18#define BOOST_JSON_NO_LIB
19#define BOOST_CONTAINER_NO_LIB
20#include <boost/json/serialize.hpp>
21#include <boost/json/parse.hpp>
22#include <boost/json/value_from.hpp>
23#include <boost/redis/resp3/serialization.hpp>
24#include <boost/json/src.hpp>
25
26namespace net = boost::asio;
27using namespace boost::describe;
33
34// Struct that will be stored in Redis using json serialization.
35struct user {
36 std::string name;
37 std::string age;
38 std::string country;
39};
40
41// The type must be described for serialization to work.
42BOOST_DESCRIBE_STRUCT(user, (), (name, age, country))
43
44// Boost.Redis customization points (examples/json.hpp)
45void boost_redis_to_bulk(std::string& to, user const& u)
46 { boost::redis::resp3::boost_redis_to_bulk(to, boost::json::serialize(boost::json::value_from(u))); }
47
48void boost_redis_from_bulk(user& u, std::string_view sv, boost::system::error_code&)
49 { u = boost::json::value_to<user>(boost::json::parse(sv)); }
50
51auto co_main(config cfg) -> net::awaitable<void>
52{
53 auto ex = co_await net::this_coro::executor;
54 auto conn = std::make_shared<connection>(ex);
55 conn->async_run(cfg, {}, net::consign(net::detached, conn));
56
57 // user object that will be stored in Redis in json format.
58 user const u{"Joao", "58", "Brazil"};
59
60 // Stores and retrieves in the same request.
61 request req;
62 req.push("SET", "json-key", u); // Stores in Redis.
63 req.push("GET", "json-key"); // Retrieves from Redis.
64
65 response<ignore_t, user> resp;
66
67 co_await conn->async_exec(req, resp, net::deferred);
68 conn->cancel();
69
70 // Prints the first ping
71 std::cout
72 << "Name: " << std::get<1>(resp).value().name << "\n"
73 << "Age: " << std::get<1>(resp).value().age << "\n"
74 << "Country: " << std::get<1>(resp).value().country << "\n";
75}
76
77#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
void boost_redis_to_bulk(std::string &payload, std::string_view data)
Adds a bulk to the request.
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
Configure parameters used by the connection classes.
Definition: config.hpp:30