Loading...
Searching...
No Matches
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
9#include <boost/asio/consign.hpp>
10#include <boost/asio/detached.hpp>
11#include <boost/asio/use_awaitable.hpp>
12#include <boost/describe.hpp>
13
14#include <iostream>
15#include <string>
16
17#if defined(BOOST_ASIO_HAS_CO_AWAIT)
18
19#include <boost/redis/resp3/serialization.hpp>
20
21#include <boost/json/parse.hpp>
22#include <boost/json/serialize.hpp>
23#include <boost/json/value_from.hpp>
24#include <boost/json/value_to.hpp>
25
26namespace asio = boost::asio;
27namespace resp3 = boost::redis::resp3;
28using namespace boost::describe;
35
36// Struct that will be stored in Redis using json serialization.
37struct user {
38 std::string name;
39 std::string age;
40 std::string country;
41};
42
43// The type must be described for serialization to work.
44BOOST_DESCRIBE_STRUCT(user, (), (name, age, country))
45
46// Boost.Redis customization points (example/json.hpp)
47void boost_redis_to_bulk(std::string& to, user const& u)
48{
49 resp3::boost_redis_to_bulk(to, boost::json::serialize(boost::json::value_from(u)));
50}
51
52void boost_redis_from_bulk(user& u, node_view const& node, boost::system::error_code&)
53{
54 u = boost::json::value_to<user>(boost::json::parse(node.value));
55}
56
57auto co_main(config cfg) -> asio::awaitable<void>
58{
59 auto ex = co_await asio::this_coro::executor;
60 auto conn = std::make_shared<connection>(ex);
61 conn->async_run(cfg, asio::consign(asio::detached, conn));
62
63 // user object that will be stored in Redis in json format.
64 user const u{"Joao", "58", "Brazil"};
65
66 // Stores and retrieves in the same request.
67 request req;
68 req.push("SET", "json-key", u); // Stores in Redis.
69 req.push("GET", "json-key"); // Retrieves from Redis.
70
71 response<ignore_t, user> resp;
72
73 co_await conn->async_exec(req, resp);
74 conn->cancel();
75
76 // Prints the first ping
77 std::cout << "Name: " << std::get<1>(resp).value().name << "\n"
78 << "Age: " << std::get<1>(resp).value().age << "\n"
79 << "Country: " << std::get<1>(resp).value().country << "\n";
80}
81
82#endif // defined(BOOST_ASIO_HAS_CO_AWAIT)
A basic_connection that type erases the executor.
Creates Redis requests.
Definition request.hpp:46
std::decay_t< decltype(std::ignore)> ignore_t
Type used to ignore responses.
Definition ignore.hpp:30
basic_node< std::string > node
A node in the response tree that owns its data.
Definition node.hpp:62
std::tuple< adapter::result< Ts >... > response
Response with compile-time size.
Definition response.hpp:25
Configure parameters used by the connection classes.
Definition config.hpp:30
A node in the response tree.
Definition node.hpp:28