使用Hiredis接口(Synchronous API)编写Redis客户端的方法

本文详细介绍了如何使用Hiredis的同步API来编写Redis客户端,包括连接Redis服务器、执行Redis命令及释放资源的过程。通过示例代码展示了添加和查询数据的具体操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要介绍使用Hiredis接口(Synchronous API)编写Redis客户端的方法。

1 Hiredis概述

引用GitHub上的描述:

Hiredis is a minimalistic C client library for the Redis database.

2 Redis客户端示例

使用Hiredis的Synchronous API接口编写Redis的客户端,通常需要调用以下几个函数:

redisContext *redisConnect(const char *ip, int port);          // 建立redis连接
void *redisCommand(redisContext *c, const char *format, ...);  // 执行redis命令
void freeReplyObject(void *reply);                             // 释放redis命令的返回内容

2.1 示例代码

完整的示例代码(hiredis_syncAPI.cpp)如下:

#include <iostream>
#include "hiredis/hiredis.h"

using namespace std;

int main()
{
    // 建立redis连接
    redisContext *c = redisConnect("192.168.213.133", 6379);
    if ((c == NULL) || (c->err))
    {
        if (c)
        {
            cout << "Error: " << c->errstr << endl;
            // 释放redis连接
            redisFree(c);
            return -1;
        }
        else
        {
            cout << "Can't allocate redis context." << endl;
            return -1;
        }
    }
    else
    {
        cout << "Connected to Redis." << endl;
    }

    redisReply *reply;

    // 添加数据
    reply = (redisReply *)redisCommand(c, "SET zs zhanshi");
    cout << "SET reply is: " << reply->str << endl;
    freeReplyObject(reply);

    // 查询数据
    reply = (redisReply *)redisCommand(c, "GET zs");
    cout << "GET reply is: " << reply->str << endl;
    freeReplyObject(reply);

    // 释放redis连接
    redisFree(c);
    
    return 0;
}

2.2 编译Redis客户端

执行下面的命令编译上述代码,生成Redis客户端:

g++ -o hiredis_syncAPI hiredis_syncAPI.cpp -lhiredis

2.3 测试Redis客户端

2.3.1 启动Redis服务器

在主机(IP地址为“192.168.213.133”)上打开Redis服务器,该Redis服务器监听对于“192.168.213.133”的连接,如下:

[root@node1 /opt/liitdar/hiredis]# redis-server /etc/redis.conf

2.3.2 启动Redis客户端

在另外一台主机(IP地址为“192.168.213.131”)上运行前面编译生成的Redis客户端“hiredis_syncAPI”,如下:

./hiredis_syncAPI

2.3.3 观察测试结果

正常情况下,我们编写的客户端能够连接到Redis服务器,并执行指定的Redis命令,如下:

如果运行Redis客户端的终端中出现上述信息,说明我们的编写的Redis客户端运行成功了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liitdar

赠人玫瑰,手有余香,君与吾共勉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值