C++ 17 添加于 Boost 1.84.0
本次发布
依赖项
Boost.Redis
Boost.Redis 是一个高级 Redis 客户端库,构建于 Boost.Asio 之上,实现了 Redis 协议 RESP3。
完整文档 在此。
要求
使用 Boost.Redis 的要求是
- Boost 1.84 或更高版本。Boost.Redis 自 Boost 1.84 起已包含在 Boost 安装中。
- C++17 或更高版本。支持的编译器包括 gcc 11 及更高版本,clang 11 及更高版本,以及 Visual Studio 16 (2019) 及更高版本。
- Redis 6 或更高版本(必须支持 RESP3)。
- OpenSSL。
文档假定具备关于 Redis 和 Boost.Asio 的基础知识。
构建库
要使用该库,必须在您的应用程序中至少包含以下内容
#include <boost/redis/src.hpp>
在恰好一个源文件中。否则,该库是仅头文件库。
Boost.Redis 无条件要求 OpenSSL。使用 Boost.Redis 的目标需要链接到 OpenSSL 库。
教程
下面的代码使用一个短暂的连接来 ping Redis 服务器
#include <boost/redis/connection.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/consign.hpp>
#include <boost/asio/detached.hpp>
#include <iostream>
namespace net = boost::asio;
using boost::redis::request;
using boost::redis::response;
using boost::redis::config;
using boost::redis::connection;
auto co_main(config const& cfg) -> net::awaitable<void>
{
auto conn = std::make_shared<connection>(co_await net::this_coro::executor);
conn->async_run(cfg, {}, net::consign(net::detached, conn));
// A request containing only a ping command.
request req;
req.push("PING", "Hello world");
// Response object.
response<std::string> resp;
// Executes the request.
co_await conn->async_exec(req, resp);
conn->cancel();
std::cout << "PING: " << std::get<0>(resp).value() << std::endl;
}
async_run 和 async_exec 函数所扮演的角色是
connection::async_exec:执行请求中包含的命令,并将各个响应存储在响应对象中。可以从您代码中的多个位置并发调用。connection::async_run:保持连接健康。它负责主机名解析、会话建立、健康检查、重新连接以及低级读写操作的协调。每个连接应仅调用一次,无论执行多少请求。
服务器推送
Redis 服务器还可以向客户端发送各种推送。其中一些是
连接类通过 connection::async_receive 函数支持服务器推送,该函数可以在用于执行命令的同一连接上调用。下面的协程展示了如何使用它
auto
receiver(std::shared_ptr<connection> conn) -> net::awaitable<void>
{
request req;
req.push("SUBSCRIBE", "channel");
generic_response resp;
conn->set_receive_response(resp);
// Loop while reconnection is enabled
while (conn->will_reconnect()) {
// Reconnect to channels.
co_await conn->async_exec(req, ignore);
// Loop reading Redis pushes.
for (;;) {
error_code ec;
co_await conn->async_receive(resp, net::redirect_error(net::use_awaitable, ec));
if (ec)
break; // Connection lost, break so we can reconnect to channels.
// Use the response resp in some way and then clear it.
...
consume_one(resp);
}
}
}
进一步阅读
完整文档 在此。