Boost
arrow_drop_down
Boost.Redis
M
D

本次发布

Marcelo Zimbres
Marcelo Zimbres
作者
Anarthal (Rubén Pérez)
Anarthal (Rubén Pérez)
贡献者

依赖项

添加了

Boost.Redis

Boost.Redis 是一个高级 Redis 客户端库,构建在 Boost.Asio 之上,并实现了 Redis 协议 RESP3

完整文档在此

要求

使用 Boost.Redis 的要求是

  • Boost 1.84 或更高版本。自 Boost 1.84 起,Boost.Redis 已包含在 Boost 安装中。
  • C++17 或更高版本。支持的编译器包括 gcc 11 及更高版本、clang 11 及更高版本以及 Visual Studio 16 (2019) 及更高版本。
  • Redis 6 或更高版本(必须支持 RESP3)。
  • OpenSSL。

文档假设具备关于 RedisBoost.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_runasync_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);
      }
   }
}

深入阅读

完整文档在此

全部时间

Rene Rivera
Rene Rivera
贡献者
Dirk Stolle
Dirk Stolle
贡献者