您的位置:首页 > 数据库 > Redis

c++中使用 hiredis/hiredis.h

2015-12-03 14:27 507 查看
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. */

};

其中,tv_sec为Epoch到创建struct timeval时的秒数,tv_usec为微秒数,即秒后面的零头

/*
作用:执行命令
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()所产生的连接。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: