生产环境应选用 redis-plus-plus。它基于 hiredis,提供 c++17 接口,支持连接池、异步和事务,需正确配置 hiredis 依赖、头文件路径及超时参数,注意字符串处理、optional 解包和 pipeline 使用规范。

Redis C++ 客户端选哪个才不踩坑
别用 redis-cplusplus(已十年未更新)、也别自己封装 hiredis C 接口——生产环境直接上 redis-plus-plus。它基于 hiredis,但提供了现代 C++17 接口,支持连接池、异步、事务,且文档虽简但示例可直接跑通。
- 编译依赖必须装
hiredis1.0.0+(ubuntu/debian:`sudo apt install libhiredis-dev`;macos:`brew install hiredis`) - CMake 中要显式 find_package(
hiredis),否则链接会报undefined reference to redisConnect - 头文件路径不是
#include "redis++.h",而是#include "sw/redis++/redis++.h"(注意命名空间路径)
连接 Redis 失败时先查这三件事
连不上不是代码写错了,大概率是配置或网络链路问题。错误常表现为 ConnectionError 或程序卡在 Redis::Redis(const ConnectionOptions&) 构造里。
- 检查
ConnectionOptions.host是否写成了"localhost"—— docker 容器内要用宿主 IP(如"172.17.0.1")或"host.docker.internal" -
ConnectionOptions.port默认是6379,但某些云 Redis 实例强制走 TLS,得设ConnectionOptions.ssl = true并配证书路径 - 超时参数不设会无限阻塞:
ConnectionOptions.connect_timeout = std::chrono::milliseconds(1000)和socket_timeout都得显式指定
set/get 字符串时 String 和 const char* 别混用
redis.set("key", "value") 看似简单,但传 std::string 和裸指针行为不同:前者自动处理长度,后者若没带 len 参数,会调 strlen——遇到含 <p><code>redis.set("key", "value") 看似简单,但传 std::string 和裸指针行为不同:前者自动处理长度,后者若没带 len 参数,会调 strlen——遇到含