c++ 连redis

今天,本人来学习如何用C++来操作redis数据库。通过hiredis.h接口来实现,目前只能在Linux环境使用。

hiredis.h的下载地址为:https://github.com/redis/hiredis

主要包括如下四个方法

1. redisContext* redisConnect(const char *ip, int port)

该函数用来连接redis数据库, 两个参数分别是redis数据库的ip和端口,端口号一般为6379。类似的还提供了一个函数,供连接超时限定,即

redisContext* redisConnectWithTimeout(const char *ip, int port, timeval tv)。

2. void *redisCommand(redisContext *c, const char *format...)

该函数用于执行redis数据库中的命令,第一个参数为连接数据库返回的redisContext,剩下的参数为变参,如同C语言中的prinf()函数。此函数的返回值为void*,但是一般会强制转换为redisReply类型,以便做进一步的处理。

3. void freeReplyObject(void *reply)

释放redisCommand执行后返回的的redisReply所占用的内存。

4. void redisFree(redisContext *c)

释放redisConnect()所产生的连接。

接下来就是就让本人来教大家如何安装hiredis吧!

首先上网站下载hiredis.tar.gz包,解压后发现里面有一个Makefile文件,然后执行make进行编译,得到

接下来把libhiredis.so放到/usr/local/lib/中,把hiredis.h放到/usr/local/inlcude/hiredis/中。

或者直接用命令make install配置。如下图

接下来在程序中就可以直接用了。在程序中包含#include <hiredis/hiredis.h>即可。

为了操作方便,一般情况下我们需要写一个头文件类,这个类的方法根据自己项目需要适当添加。如下

代码:redis.h

#ifndef _REDIS_H_
#define _REDIS_H_

#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>

#include <hiredis/hiredis.h>

class Redis
{
public:

    Redis(){}

    ~Redis()
 {
        this->_connect = NULL;
  this->_reply = NULL;        
 }

 bool connect(std::string host, int port)
 {
    this->_connect = redisConnect(host.c_str(), port);
  if(this->_connect != NULL && this->_connect->err)
  {
      printf("connect error: %s\n", this->_connect->errstr);
   return 0;
  }
  return 1;
 }

    std::string get(std::string key)
 {
  this->_reply = (redisReply*)redisCommand(this->_connect, "GET %s", key.c_str());
  std::string str = this->_reply->str;
  freeReplyObject(this->_reply);
  return str;
 }

 void set(std::string key, std::string value)
 {
        redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
 }

private:

    redisContext* _connect;
 redisReply* _reply;
    
};

#endif  //_REDIS_H_

redis.cpp

#include "redis.h"

int main()
{
 Redis *r = new Redis();
 if(!r->connect("192.168.13.128", 6379))
 {
  printf("connect error!\n");
  return 0;
 }
 r->set("name", "Mayuyu");
 printf("Get the name is %s\n", r->get("name").c_str());
 delete r;
 return 0;
}

Makefile文件

redis: redis.cpp redis.h
 g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis

clean:
 rm redis.o redis

注意在g++和rm之前都是一个tab键。

在编译的时候需要加参数,假设文件为redis.cpp,那么编译命令如下

g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis

在执行的时候如果出现动态库无法加载,那么需要进行如下配置

在/etc/ld.so.conf.d/目录下新建文件usr-libs.conf,内容是:/usr/local/lib

如下图所示

然后使用命令/sbin/ldconfig更新一下配置即可。

C++连接 Redis,最常用的方法是使用第三方库 **hiredis**(Redis 官方推荐的 C 客户端),然后通过 C++ 封装或使用基于 hiredisC++ 封装库如 **hiredis++** 或 **redis-plus-plus**。下面我将详细介绍如何使用 **redis-plus-plus**(现代、易用、功能完整)来连接和操作 Redis。 --- ### ✅ 推荐方案:使用 `redis-plus-plus` `redis-plus-plus` 是一个现代 C++ (C++11 及以上) Redis 客户端,基于 hiredis 构建,支持同步/异步操作、连接池、Pipeline、发布订阅等。 --- ## 一、安装依赖 ### 1. 安装 hiredisredis-plus-plus #### Ubuntu / Debian: ```bash # 安装编译工具链 sudo apt-get update sudo apt-get install build-essential git cmake # 克隆并编译安装 hiredis git clone https://github.com/redis/hiredis.git cd hiredis make && sudo make install sudo ldconfig # 更新共享库缓存 # 克隆并安装 redis-plus-plus cd .. git clone https://github.com/sewenew/redis-plus-plus.git cd redis-plus-plus mkdir build && cd build cmake .. make && sudo make install ``` > 注意:确保 `libhiredis.so` 和 `libredis++.so` 被正确安装到系统路径。 --- ## 二、C++ 示例代码:连接 Redis 并执行基本操作 ```cpp #include <iostream> #include <sw/redis++/redis++.h> int main() { try { // 创建 Redis 连接对象(默认连接到 127.0.0.1:6379) sw::redis::ConnectionOptions connection_options; connection_options.host = "127.0.0.1"; // Redis 地址 connection_options.port = 6379; // 端口 connection_options.db = 0; // 数据库编号 // 如果有密码,取消下一行注释: // connection_options.password = "yourpassword"; sw::redis::Redis redis(connection_options); // SET 操作 redis.set("name", "Alice"); std::cout << "Set key 'name' to 'Alice'" << std::endl; // GET 操作 auto val = redis.get("name"); // 返回 OptionalString if (val) { std::cout << "Get name: " << *val << std::endl; } else { std::cout << "Key 'name' not found" << std::endl; } // INCR 操作 redis.set("counter", "100"); long long cnt = redis.incr("counter"); std::cout << "Counter after INCR: " << cnt << std::endl; // LPUSH + LRANGE redis.lpush("mylist", {"world", "hello"}); std::vector<std::string> list; redis.lrange("mylist", 0, -1, std::back_inserter(list)); std::cout << "List content: "; for (const auto& s : list) std::cout << s << " "; std::cout << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } ``` --- ## 三、编译命令 假设你的源文件名为 `redis_demo.cpp`: ```bash g++ -std=c++11 redis_demo.cpp -lredis++ -lhiredis -o redis_demo ``` 运行程序: ```bash ./redis_demo ``` 输出示例: ``` Set key 'name' to 'Alice' Get name: Alice Counter after INCR: 101 List content: hello world ``` --- ## 四、解释说明 | 组件 | 作用 | |------|------| | `ConnectionOptions` | 配置 Redis 连接参数(host, port, db, password 等) | | `Redis` 类 | 提供所有 Redis 命令接口(set/get/incr/lpush 等) | | `redis.get()` | 返回 `Optional<std::string>`,可用 `if(val)` 判断是否存在 | | 异常处理 | 所有错误抛出 `std::exception` 子类,建议用 try-catch 包裹 | --- ## 五、高级功能(可选) ### 使用连接池(适用于多线程服务) ```cpp sw::redis::ConnectionPoolOptions pool_opts; pool_opts.size = 3; // 连接池大小 sw::redis::Redis redis(connection_options, pool_opts); ``` ### 发布/订阅 示例 ```cpp auto sub = redis.subscriber(); sub.on_message([](const std::string& channel, const std::string& msg) { std::cout << "Received: " << msg << " from channel: " << channel << std::endl; }); sub.subscribe("chat"); // 在另一个终端用 redis-cli 发布消息测试: // PUBLISH chat "Hello Redis" ``` --- ## 六、常见问题排查 - ❌ 报错 `undefined reference to redis++`:确认是否链接了 `-lredis++ -lhiredis` - ❌ 连接拒绝:检查 Redis 是否运行 `redis-server` - ❌ 找不到头文件:确认 `#include <sw/redis++/...>` 路径正确,CMake 或编译器能找到安装路径 - ✅ 推荐使用 CMake 管理项目(见下文扩展) --- ### 📦 使用 CMake 的 `CMakeLists.txt` 示例 ```cmake cmake_minimum_required(VERSION 3.10) project(redis_cpp_example) set(CMAKE_CXX_STANDARD 11) find_package(hiredis REQUIRED) find_package(redis++ REQUIRED) add_executable(redis_demo redis_demo.cpp) target_link_libraries(redis_demo PRIVATE hiredis::hiredis redis++::redis++) ``` ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值