2
0
mirror of https://github.com/boostorg/redis.git synced 2026-02-21 15:22:14 +00:00
Files
redis/examples/pubsub.cpp
2021-10-31 22:05:38 +01:00

82 lines
2.0 KiB
C++

/* Copyright (c) 2019 - 2021 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 "utils.ipp"
using namespace aedis;
net::awaitable<void> publisher()
{
auto ex = net::this_coro::executor;
auto socket = co_await make_connection();
std::queue<resp3::request> requests;
requests.push({});
requests.back().push(command::hello, 3);
requests.back().push(command::publish, "channel1", "Message to channel1");
requests.back().push(command::publish, "channel2", "Message to channel2");
requests.back().push(command::quit);
resp3::stream<tcp_socket> stream{std::move(socket)};
for (;;) {
resp3::response resp;
co_await stream.async_consume(requests, resp);
}
}
net::awaitable<void> subscriber()
{
auto ex = net::this_coro::executor;
auto socket = co_await make_connection();
std::string id;
std::queue<resp3::request> requests;
requests.push({});
requests.back().push(command::hello, "3");
requests.back().push(command::subscribe, "channel1", "channel2");
resp3::stream<tcp_socket> stream{std::move(socket)};
for (;;) {
resp3::response resp;
co_await stream.async_consume(requests, resp);
if (resp.get_type() == resp3::type::push) {
std::cout
<< "Subscriber " << id << "\n"
<< resp << std::endl;
continue;
}
auto const cmd = requests.front().commands.front();
switch (cmd) {
case command::hello:
id = resp.raw().at(8).data;
break;
default:
std::cout
<< cmd << "\n"
<< resp << 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);
co_spawn(ioc, publisher(), net::detached);
ioc.run();
}