Redis 客户端C++使用

安装 redis-plus-plus

在C++中使用Redis,通常需要借助第三方库来实现与Redis服务器的交互。目前比较流行的库有 redis-plus-plushiredisredis-plus-plus 是基于 hiredis 实现的,hiredis 是⼀个 C 语⾔实现的 redis 客⼾端,因此需要先安装 **hiredis,**直接使⽤包管理器安装即可。
Ubuntu

bash 复制代码
apt install libhiredis-dev

Centos

复制代码
​​​​​​​yum install hiredis-devel.x86_64

之后通过源码编译安装 redis-plus-plus

bash 复制代码
#下载 redis-plus-plus 源码
git clone https://github.com/sewenew/redis-plus-plus.git
#使⽤ cmake 构建
cd redis-plus-plus
mkdir build #创建build目录,放入编译生成的文件,避免污染源代码
cd build 
cmake .. #生成mafile文件
make #编译
make install #把库拷贝到系统目录

构建成功后, 会在 /usr/local/include/ 中多出 sw ⽬录, 并且内部包含 redis++ 的⼀系列头⽂件,由于我们已经把该目录拷贝到系统目录下,所以当我们使用 redis++ 中的接口函数时就需要包含头文件<sw/redis++/redis++.h>。

在 /usr/local/lib/ 中则是多出⼀系列 libredis 库⽂件。

详细 API

参考:
Github 地址: https://github.com/sewenew/redis-plus-plus/blob/master/src/sw/redis++/redis.h
同步到 gitee 后的地址: https://gitee.com/peixinchen2/redis-plus-plus/blob/master/src/sw/redis++/redis.h

使用案例

redis++.cc

cpp 复制代码
#include <iostream>
#include "sw/redis++/redis++.h"
using namespace std;

int main()
{
    // 创建redis连接,基于tcp的应用层协议+ip+端口
    sw::redis::Redis redis("tcp://127.0.0.1:6379");
    // 检查连接是否成功
    string ret = redis.ping();
    cout << ret << endl;

    redis.flushall();
    redis.set("key1", "111");
    redis.set("key2", "222");
    sw::redis::OptionalString value1 = redis.get("key1");
    auto value2 = redis.get("key2");
    cout << value1.value() << endl;
    cout << value2.value() << endl;

    vector<string> v;                  // 用来存储 keys 返回结果的容器
    auto it = back_insert_iterator(v); // 尾插迭代器
    redis.keys("*", it);
    for (auto &e : v)
        cout << e << endl;
    return 0;
}

makefile

使用 makefile 编译程序时需要引入库文件,如 redis++ 的库,hiredis 的库,线程库。首先需要使用 find 命令找到相关库文件的路径,例如:

需要连接动态库或者静态库看自己选择,为了方便,此处我们选择直接连接动态库

bash 复制代码
test:redis++.cc
	g++ -o $@ $^ -std=c++20 -lpthread /usr/local/lib/libredis++.a  /usr/lib/x86_64-linux-gnu/libhiredis.a
.PHONY:clean
clean:
	rm -f test
相关推荐
Databend4 分钟前
Databend 产品更新:从 Spatial Index Join 到 Eval 数据管道
大数据·数据库·sql
数据知道8 分钟前
SQL 注入从入门到精通:手工注入 + sqlmap 自动化
网络·数据库·sql·网络安全·自动化
lilian23315 分钟前
Harmony os 技术实战|拼豆制图06:收藏 ID、生成记录与重启恢复怎么不打架
android·java·数据库·harmonyos
2601_9557596222 分钟前
ClaudeAPI成本中心与业务标签设计指南
android·java·数据库
仙人球部落 揞殺25 分钟前
Sql Server查询性能优化之走出索引的误区
数据库·性能优化
Bryce学亮28 分钟前
FileLine,基于 Qt 6 + QML 构建的跨平台文件传输与即时通讯工具
数据库·c++·人工智能·python·qt·github
轻揉小乔 真新人1 小时前
T-SQL查询进阶—理解SQL Server中的锁
服务器·数据库·sql
全麦面包 time展天2 小时前
走向DBA[MSSQL篇] 从SQL语句的角度 提高数据库的访问性能
数据库·sqlserver·dba
刘某的Cloud2 小时前
Galera Cluster mariadb 生产环境常见问题排查与运维指南
linux·运维·数据库·mariadb·集群高可用
雨辰AI2 小时前
K8s 国产数据库慢 SQL 自动监控|Prometheus+Grafana 可视化全落地
数据库·sql·安全·容器·kubernetes·grafana·prometheus