Redis C API的定义及使用方法:

API:


redisContext *redisConnect(const char *ip, int port);
redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv);
redisContext *redisConnectNonBlock(const char *ip, int port);


void *redisCommand(redisContext *c, const char *format, ...);
redisReply *reply = (redisReply*)redisCommand(m_pContext, "SELECT %d", m_pCachePool->GetDBNum());


void freeReplyObject(void *reply);	//释放redisCommand返回的对象
void redisFree(redisContext *c);	//释放redisConnect返回的对象

1. redisConnect:

redisConnect() 用于返回一个“redisContext”句柄,用于维护一个Redis连接的状态信息。
struct redisContext 结构体中有一个“int err”成员,用于指示连接是否发生错误。
【redisContext 不是 线程安全的。】

使用举例:

redisContext *c = redisConnect("127.0.0.1", 6379);
if( c == NULL || c->err ) {
	if(c) {
		printf("Error: %s\n", c->errstr);
	}
}
else {
	printf("NULL, can't allocate redis context\n");
}

struct redisContext 结构体内容:

typedef struct redisContext {
	int 			err;
	char			errstr[128];
	int				fd;
	int				flags;
	char*			obuf;
	redisReader* 	reader;
} redisContext;

2. redisCommand :

redisCommand 用于发送命令:

redisReply *reply = (redisReply*)redisCommand((redisContext*)context, "SET foo bar");
if(reply && (reply->type == REDIS_REPLY_STATUS) && (strncmp(reply->str, "OK", 2)==0 ) )) {
	freeReplyObject(reply);
	return 0;
} 
else {
	log("select cache db failed");
	return 2;
}

struct redisReply 结构体内容:

typedef struct redisReply {
	int					 type;		// REDIS_REPLY_* : 返回类型
	long long			 integer;
	int					 len;
	char*				 str;
	size_t				 elements;
	struct redisReply**  element;
} redisReply;

因不同的redis查询语句返回的信息类型不同,通过 redisReply结构体中的 type 字段进行表示:

REDIS_REPLY_STATUS, 	reply->str, reply->len	//当回复类型是REDIS_REPLY_STATUS时,返回值存储在reply->str中
REDIS_REPLY_ERROR, 
REDIS_REPLY_INTEGER, 	reply->integer  		//返回值存储在 reply->integer 中
REDIS_REPLY_NIL, 		The command replied with a nil object. There is no data to access.
REDIS_REPLY_STRING, 	reply->str, reply->len
REDIS_REPLY_ARRAY,		reply->elements, reply->element[idx]

例如:

//string:
> set key value
OK

> get key
"value"

//hash:
> hset key1 field1 value1
(integer) 1

> hget key1 field1
"value1"

//list:
> lpush lkey1 element1 element2 element3
(integer) 3

3. redisFree :

使用redisFree断开连接并释放资源:

使用举例:

redisFree((redisContext*)context);

4. freeReplyObject:

redisCommand 返回的查询结果 redisReply 结构体,必须使用 freeReplyObject 函数显式的释放。

void freeReplyObject(void *reply);

遗留问题:

数据库连接池的数量设置为多大合适?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值