hiredis是redis开源库对外发布的客户端API包。

当redis-server配置启动后,可以通过hiredis操作redis资源。

主要分为:

  strings、hash、lists、sets、sort sets

hiredis使用较为简单,下面是几个主要的函数和对象:

 /*
作用:用于连接redis服务器
ip : 为redis的ip地址;
port: 端口地址;
tv:连接超时的参数;
*/
redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv);
/*
作用:执行命令
c:redisConnectWitTimeout返回的对象;
format:命令参数;
*/ void *redisCommand(redisContext *c, const char *format, ...)
 /*
说明:redisCommand返回的对象指针,也就是已经命令返回的结果数据
*/ typedef struct redisReply {
int type; /* REDIS_REPLY_* */
long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
int len; /* Length of string */
char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;

来一个具体的实例

 /*需要配置,才能编译通过*/
#include <iostream>
#include "hiredis.h" #define MAX_LEN 64 int main()
{
timeval timeout = {,};
char ip[MAX_LEN],passwd[MAX_LEN];
memset(ip,,MAX_LEN);
memset(passwd,,MAX_LEN);
sprintf(ip,"*****");
sprintf(passwd,"******");
uint32_t port = ;
redisContext *m_pRedisContext = redisConnectWithTimeout(ip,port,timeout);
if(m_pRedisContext->err){
std::cout << "log, redis connect error\n";
return ;
} redisReply *reply = static_cast<redisReply*>(redisCommand(m_pRedisContext,\
"AUTH %s",passwd));
if(!reply){
std::cout << "log, redis command error, " << m_pRedisContext->errstr << \
std::endl;
return ;
} std::cout << "AUTH " << passwd << reply->str << std::endl;
freeReplyObject(reply); //create datadase id = 1;
uint32_t index = ;
reply = static_cast<redisReply*>(redisCommand(m_pRedisContext,"SELECT %d",));
if(!reply) {
std::cout << "log, redis command error," << m_pRedisContext->errstr << \
std::endl;
freeReplyObject(reply);
return ;
} std::cout << "SELECT " << index << reply->str << std::endl;
freeReplyObject(reply); uint32_t id = ;
reply = static_cast<redisReply*>(redisCommand(m_pRedisContext, \
"HMSET user:%u %s %s %s %s",id,"name","xuxu","age",""));
if(!reply){
std::cout << "log, redis command error," << m_pRedisContext->errstr << \
std::endl;
freeReplyObject(reply);
return ;
} reply = static_cast<redisReply*>(redisCommand(m_pRedisContext,\
"SET name:%s %s","","liushun"));
if(!reply){
std::cout << "log, redis command error, " << m_pRedisContext->errstr << \
std::endl;
freeReplyObject(reply);
return ;
} reply = static_cast<redisReply*>(redisCommand(m_pRedisContext,"GET name:%s",""));
if(!reply){
std::cout << "log, redis command error," << m_pRedisContext->errstr << \
std::endl;
freeReplyObject(reply);
return ;
} std::cout << reply->str << std::endl;
freeReplyObject(reply); return ;
}
05-11 13:31