使用hiredis库可在C++中高效操作Redis。首先安装hiredis,Ubuntu/Debian执行sudo apt-get install libhiredis-dev,CentOS/RHEL执行sudo yum install hiredis-devel,或从GitHub源码编译安装。接着编写C++程序,包含<hiredis/hiredis.h>头文件,使用redisConnect连接Redis服务器,redisCommand发送命令,如SET和GET,通过检查redisReply的type字段处理不同回复类型,如REDIS_REPLY_STRING、REDIS_REPLY_STATUS等,操作完成后调用freeReplyObject释放内存,最后用redisFree关闭连接。可将常用操作封装成C++类提高复用性,如定义RedisClient类封装连接、SET、GET方法。编译时需链接hiredis库:g++ redis_test.cpp -lhiredis -o redis_test。注意事项包括确保Redis服务运行、及时释放内存、生产环境添加超时与重试机制,适合高性能、嵌入式场景。

要在C++中操作Redis数据库,最常用的方式是使用 hiredis —— Redis官方推荐的C语言客户端库。由于C++兼容C,可以直接使用 hiredis 并封装成更易用的C++接口。下面介绍如何在C++项目中集成和使用 hiredis 与 Redis 进行交互。
首先需要在系统中安装 hiredis。可以通过源码编译或包管理器安装。
Ubuntu/Debian:
sudo apt-get update sudo apt-get install libhiredis-dev
CentOS/RHEL:
立即学习“C++免费学习笔记(深入)”;
sudo yum install hiredis-devel
从源码安装:
git clone https://github.com/redis/hiredis.git cd hiredis make sudo make install sudo ldconfig # 刷新共享库缓存
使用 hiredis 的基本流程包括:建立连接、发送命令、获取回复、断开连接。
以下是一个简单的 C++ 示例,演示如何连接 Redis 并执行 SET 和 GET 操作:
#include <iostream>
#include <string>
#include <hiredis/hiredis.h>
<p>int main() {
// 建立同步连接
redisContext *ctx = redisConnect("127.0.0.1", 6379);
if (ctx == nullptr || ctx->err) {
if (ctx) {
std::cerr << "Connection error: " << ctx->errstr << std::endl;
} else {
std::cerr << "Context creation failed" << std::endl;
}
return 1;
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 执行 SET 命令
redisReply *reply = (redisReply*)redisCommand(ctx, "SET %s %s", "name", "Tom");
if (reply && reply->type == REDIS_REPLY_STATUS && (std::string(reply->str) == "OK")) {
std::cout << "SET successful" << std::endl;
} else {
std::cerr << "SET failed" << std::endl;
}
freeReplyObject(reply);
// 执行 GET 命令
reply = (redisReply*)redisCommand(ctx, "GET %s", "name");
if (reply && reply->type == REDIS_REPLY_STRING) {
std::cout << "GET name = " << reply->str << std::endl;
} else {
std::cerr << "GET failed or key not found" << std::endl;
}
freeReplyObject(reply);
// 关闭连接
redisFree(ctx);
return 0;}
编译时需链接 hiredis 库。假设源文件名为 redis_test.cpp,使用如下命令编译:
g++ redis_test.cpp -lhiredis -o redis_test
运行程序:
./redis_test
输出应为:
SET successful GET name = Tom
Redis 命令返回的回复类型多样,redisReply 结构体中的 type 字段表示类型,常见值包括:
示例:遍历列表(LIST)类型数据:
reply = (redisReply*)redisCommand(ctx, "LRANGE %s 0 -1", "mylist");
if (reply && reply->type == REDIS_REPLY_ARRAY) {
for (size_t i = 0; i < reply->elements; ++i) {
std::cout << "Item " << i << ": " << reply->element[i]->str << std::endl;
}
}
freeReplyObject(reply);
为了提升代码可读性和复用性,可以将 hiredis 封装成一个简单的 C++ 类:
#include <string>
#include <hiredis/hiredis.h>
<p>class RedisClient {
private:
redisContext *context;</p><p>public:
RedisClient(const std::string& host, int port) {
context = redisConnect(host.c_str(), port);
if (!context || context->err) {
if (context) std::cerr << "Error: " << context->errstr << std::endl;
context = nullptr;
}
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">~RedisClient() {
if (context) redisFree(context);
}
bool set(const std::string& key, const std::string& value) {
redisReply *reply = (redisReply*)redisCommand(context, "SET %s %s", key.c_str(), value.c_str());
bool ok = reply && reply->str && std::string(reply->str) == "OK";
freeReplyObject(reply);
return ok;
}
std::string get(const std::string& key) {
redisReply *reply = (redisReply*)redisCommand(context, "GET %s", key.c_str());
std::string result;
if (reply && reply->type == REDIS_REPLY_STRING) {
result = reply->str;
}
freeReplyObject(reply);
return result;
}};
使用方式:
RedisClient redis("127.0.0.1", 6379);
redis.set("city", "Beijing");
std::cout << "city = " << redis.get("city") << std::endl;
基本上就这些。使用 hiredis 在 C++ 中操作 Redis 简单高效,适合嵌入式、高性能服务等场景。
以上就是C++如何操作Redis数据库_使用hiredis库在C++中与Redis进行交互的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号