
在C++中连接和操作Redis数据库,通常使用第三方库来实现。由于Redis官方没有提供C++客户端,开发者依赖成熟的开源C++ Redis客户端库进行键值存储的访问与操作。最常用的是 hiredis(官方C客户端)配合 redis-plus-plus 这类封装良好的C++接口库。
hiredis 是Redis官方推荐的C语言客户端,性能高但API较底层。为了更方便地在C++中使用,推荐搭配 redis-plus-plus,它基于hiredis构建,提供了现代C++风格的接口(支持STL容器、异常处理等)。
安装依赖库:在Ubuntu/Debian系统上:
sudo apt-get install libhiredis-dev
立即学习“C++免费学习笔记(深入)”;
git clone https://github.com/sewenew/redis-plus-plus.git
cd redis-plus-plus && mkdir build && cd build
cmake ..
make && sudo make install
确保已安装编译工具链和cmake。
使用 redis-plus-plus 进行同步连接和基本操作:
#include <iostream>
#include <sw/redis++/redis++.h>
using namespace sw::redis;
int main() {
try {
// 创建Redis连接对象
auto redis = Redis("tcp://127.0.0.1:6379");
// 设置一个字符串键值
redis.set("name", "Alice");
// 获取值
auto val = redis.get("name");
if (val) {
std::cout << "name: " << *val << std::endl; // 输出 Alice
}
// 操作List
redis.lpush("tasks", {"task1", "task2"});
auto tasks = redis.lrange("tasks", 0, -1);
for (const auto &task : tasks) {
std::cout << "Task: " << task << std::endl;
}
// 设置带过期时间的键
redis.setex("token", std::chrono::seconds(60), "abc123");
} catch (const RedisException &e) {
std::cerr << "Redis error: " << e.what() << std::endl;
}
return 0;
}
g++ -std=c++17 your_file.cpp -lredis++ -lhiredis -pthread -o redis_demo
redis-plus-plus 支持连接池,适用于多线程环境:
// 配置连接选项
ConnectionOptions connection_opts;
connection_opts.host = "127.0.0.1";
connection_opts.port = 6379;
connection_opts.db = 0;
// 配置连接池
ConnectionPoolOptions pool_opts;
pool_opts.size = 10; // 连接池大小
Redis redis(ConnectionPool(connection_opts, pool_opts));
多个线程可安全共享同一个 Redis 对象。
也支持发布/订阅模式:
auto subscriber = redis.subscriber();
subscriber.on_message([](const std::string& channel, const std::string& msg) {
std::cout << "Channel: " << channel << ", Msg: " << msg << std::endl;
});
subscriber.subscribe("chat");
while (true) {
subscriber.poll(std::chrono::milliseconds(100));
}
始终用 try-catch 包裹Redis操作,捕获 RedisException 类型异常。网络中断、序列化错误、命令语法错误都会抛出异常。
避免长时间持有连接,建议结合RAII或智能指针管理生命周期。使用连接池时,库会自动管理底层连接的复用与释放。
基本上就这些。只要配置好库环境,C++操作Redis就跟调用本地函数一样自然。关键是选对库——redis-plus-plus 简洁高效,适合大多数项目需求。
以上就是c++++怎么连接和操作Redis数据库_c++键值存储访问与连接库使用的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号