CentOS7 使用C++连接并操作Redis ---- hiredis

7 篇文章 0 订阅

在Java中,可以直接使用 Jedis 来操作 Redis,但是在C++中要稍微麻烦一些。在 C++ 中需要使用 hiredis 动态库来操作Redis。hiredis 是 Redis 数据库的 C 接口,目前只能在 Linux 下使用。只需要几个简单基本的函数就能操作 Redis 数据库了。首先要配置好动态库环境

git clone https://github.com/redis/hiredis

make

make install

到此已经安装成功,接下来在程序中就可以直接用了,在程序中引用头文件如下:

#include <hiredis/hiredis.h>

下面介绍一些基础的API。

API介绍

redisConnect函数,原型如下。该函数用来连接 Redis 数据库,函数参数为字符串类型的 ip 地址和整型端口号。返回值为 redisContext 类型的指针。

redisContext* redisConnect(const char *ip, int port);

redisContext 包含连接相关的信息,它里面有个err字段,0表示正常,其他表示出错了!通过errstr字段可以知晓错误信息。

string ip = "192.168.44.100";
int port = 6379;
redisContext* redis = redisConnect(ip.c_str(), port);
if (redis != nullptr && redis->err != 0) {
    cout << "connect error: " << redis->err << endl;
}

redisCommand函数,原型如下。该函数执行redis数据库中的操作命令,第一个参数为连接数据库时返回的redisContext*,剩下的参数为变参,就如C标准函数printf函数一样的变参。 返回值为void*,一般强制转换成为redisReply类型,以便做进行进一步的处理。

void* redisCommand(redisContext* c, const char* format, ...);
redisReply* reply = (redisReply*)redisCommand(redis, "set key value");
redisReply* reply = (redisReply*)redisCommand(redis, "set key %s", value);
redisReply* reply = (redisReply*)redisCommand(redis, "set %s %s", key, value);

redisReply* reply = (redisReply*)redisCommand(redis, "get %s", key);
redisReply* reply = (redisReply*)redisCommand(redis, "get key");

// ...

redisCommand函数的返回值类型为,redisReply*, 我们需要通过判断它的type字段来知道返回了具体什么样的内容:

REDIS_REPLY_STATUS 表示状态,内容通过str字段查看,字符串长度是len字段
REDIS_REPLY_ERROR 表示出错,查看出错信息,如上的str,len字段
REDIS_REPLY_INTEGER 返回整数,从integer字段获取值
REDIS_REPLY_NIL 没有数据返回
REDIS_REPLY_STRING 返回字符串,查看str,len字段
REDIS_REPLY_ARRAY 返回一个数组,查看elements的值(数组个数),通过element[index]的方式访问数组元素,每个数组元素是一个redisReply对象的指针


redisCommandArgv函数,函数原型如下。和redisCommand函数差不多,但是可以批量的执行命令。

void* redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);

freeReplyObject函数,函数原型如下。用来释放 redisCommand 函数执行后返回的 redisReply 所占用的内存。

void freeReplyObject(void* reply);

redisFree函数,函数原型如下。用来断开 redisConnect 函数所产生的连接,并释放 redisContext 的内容。

void redisFree(redisContext* c);

测试案例

test.cpp内容如下:

#include <iostream>
#include <cstring>
#include <hiredis/hiredis.h>
using namespace std;

class Redis {
public:
    Redis() {}

    ~Redis() {
        redisFree(m_connect);
        this->m_connect = nullptr;
        this->m_reply = nullptr;
    }

    // 创建连接
    bool connect(string& host, int port) {
        this->m_connect = redisConnect(host.c_str(), port);
        if (this->m_connect != nullptr && this->m_connect->err) {
            cout << "connect error: " << this->m_connect->err << endl;
            return false;
        }
        return true;
    }

    // set 操作
    void set(const string& key, const string& value) {
        redisCommand(this->m_connect, "SET %s %s", key.c_str(), value.c_str());
    }

    // get 操作
    string get(const string& key) {
        this->m_reply = (redisReply*)redisCommand(this->m_connect, "GET %s", key.c_str());
        if (m_reply->type == REDIS_REPLY_NIL) return "nil";
        string str = this->m_reply->str;
        freeReplyObject(this->m_reply);
        return str;
    }

private:
    redisContext* m_connect;
    redisReply* m_reply;
};

int main() {
    string ip = "192.168.44.100";
    int port = 6379;

    Redis* redis = new Redis();
    redis->connect(ip, port);
    string operat;
    cout << "Usage: Input set(SET) or get(GET)" << endl;
    while (cin >> operat) {
        if (operat == "get" || operat == "GET") {
            string key;
            cout << "Please input key: ";
            cin >> key;
            cout << "Get the value is " << redis->get(key) << endl;
        }
        else if (operat == "set" || operat == "SET") {
            string key, value;
            cout << "Please input key value: ";
            cin >> key >> value;
            redis->set(key, value);
        }
        else {
            cout << "Usage: Input set(SET) or get(GET) to operat Redis." << endl;
        }
    }

    return 0;
}

编译运行:

makefile文件内容如下(路径要写对,-lhiredis 不能丢):

target=test
lib=test.cpp
$(target):$(lib)
	g++ -std=c++11 $^ -o $@ -I /usr/local/include/ -L /usr/local/lib -lhiredis

make,./test(一定要先确保redis服务已经开启) 执行效果如下

登录redis中查看,可以看到,键值对确实已经存在了

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值