当前位置: 首页 > article >正文

Redis 客户端C++使用

安装 redis-plus-plus

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

Ubuntu
apt install libhiredis-dev
Centos
​​​​​​​yum install hiredis-devel.x86_64
之后通过源码编译安装 redis-plus-plus
#下载 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

#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 命令找到相关库文件的路径,例如:

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

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

http://www.kler.cn/a/552937.html

相关文章:

  • GoFound 与 MySQL 集成优化方案
  • 寒假总结与心得
  • 侯捷 C++ 课程学习笔记:设计模式在面向对象开发中的应用
  • Python 爬虫入门:从基础到实战
  • 修改项目的一些前端记录(自用)
  • MySQL-慢SQL解析及调试分析思路
  • 可变列二维数组【C语言】
  • 内网常见问题处理
  • java数据结构_优先级队列(堆)_6.1
  • 开源元搜索引擎SearXNG:使用Docker详细搭建部署与使用
  • 【OS安装与使用】part4-ubuntu22.04安装anaconda
  • 【R语言】绘图
  • ONNX Runtime 与 CUDA、cuDNN 的版本对应
  • “三次握手”与“四次挥手”:TCP传输控制协议连接过程
  • 在Kubernetes上部署DeepSeek-R1进行高效AI推理
  • C#```
  • 一文读懂Docker之Docker Compose
  • 论文笔记-WSDM2024-LLMRec
  • 02.19 构造函数
  • MYSQL数据库特殊查询-INFORMATION_SCHEMA