mirror of
https://github.com/boostorg/redis.git
synced 2026-01-19 04:42:09 +00:00
87 lines
2.3 KiB
C++
87 lines
2.3 KiB
C++
/* Copyright (c) 2019 Marcelo Zimbres Silva (mzimbres at gmail dot com)
|
|
*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
|
|
#include <iostream>
|
|
#include <chrono>
|
|
|
|
#include <aedis/aedis.hpp>
|
|
#include <aedis/src.hpp>
|
|
|
|
#include "lib/net_utils.hpp"
|
|
|
|
namespace resp3 = aedis::resp3;
|
|
using aedis::redis::command;
|
|
using aedis::redis::make_serializer;
|
|
using resp3::adapt;
|
|
using resp3::node;
|
|
|
|
namespace net = aedis::net;
|
|
using net::async_write;
|
|
using net::buffer;
|
|
using net::dynamic_buffer;
|
|
|
|
/* In this example we send a subscription to a channel and start
|
|
reading server side messages indefinitely.
|
|
|
|
Notice we store the id of the connection (attributed by the redis
|
|
server) to be able to identify it (in the logs for example).
|
|
|
|
After starting the example you can test it by sending messages with
|
|
redis-cli like this
|
|
|
|
$ redis-cli -3
|
|
127.0.0.1:6379> PUBLISH channel1 some-message
|
|
(integer) 3
|
|
127.0.0.1:6379>
|
|
|
|
The messages will then appear on the terminal you are running the
|
|
example.
|
|
*/
|
|
net::awaitable<void> subscriber()
|
|
{
|
|
try {
|
|
auto socket = co_await connect();
|
|
|
|
std::string request;
|
|
auto sr = make_serializer(request);
|
|
sr.push(command::hello, "3");
|
|
sr.push(command::subscribe, "channel1", "channel2");
|
|
co_await async_write(socket, buffer(request));
|
|
|
|
std::vector<node> resp;
|
|
|
|
// Reads the response to the hello command.
|
|
std::string buffer;
|
|
co_await resp3::async_read(socket, dynamic_buffer(buffer), adapt(resp));
|
|
co_await resp3::async_read(socket, dynamic_buffer(buffer));
|
|
|
|
// Saves the id of this connection.
|
|
auto const id = resp.at(8).data;
|
|
|
|
// Loops to receive server pushes.
|
|
for (;;) {
|
|
resp.clear();
|
|
co_await resp3::async_read(socket, dynamic_buffer(buffer), adapt(resp));
|
|
|
|
std::cout
|
|
<< "Subscriber " << id << ":\n"
|
|
<< resp << std::endl;
|
|
}
|
|
} catch (std::exception const& e) {
|
|
std::cerr << e.what() << std::endl;
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
net::io_context ioc;
|
|
co_spawn(ioc, subscriber(), net::detached);
|
|
co_spawn(ioc, subscriber(), net::detached);
|
|
co_spawn(ioc, subscriber(), net::detached);
|
|
ioc.run();
|
|
}
|