hiredis是redis开源库对外发布的客户端API包。
当redis-server配置启动后,可以通过hiredis操作redis资源。
几个基本的函数就可以操作redis数据库
/* 作用:用于连接redis服务器 ip : 为redis的ip地址; port: 端口地址; tv:连接超时的参数; */ redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv);该函数用来 连接redis数据库 ,参数为数据库的ip地址和端口,一般redis数据库的端口为6379
struct timeval结构体在time.h中的定义为:
- struct timeval
- {
- __time_t tv_sec; /* Seconds. */
- __suseconds_t tv_usec; /* Microseconds. */
- };
/* 作用:执行命令 c:redisConnectWitTimeout返回的对象; format:命令参数;
一般强制转换成为redisReply类型,以便做进行进一步的处理 */ void *redisCommand(redisContext *c, const char *format, ...)
例如:
redisReply *reply = NULL;
reply = (redisReply *)redisCommand(m_c,"GET %s", key);
/* 说明: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;
void freeReplyObject(void *reply);
说明:释放redisCommand执行后返回的redisReply所占用的内存
void redisFree(redisContext *c);
说明:释放redisConnect()所产生的连接。