作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在使用 hiredis 编写一个带有异步 I/O 的 redis 客户端软件。但是当连接断开时它会崩溃,并调用 redisAsyncFree。
主循环是这样的:
RedisTask* theTask;
OSQueueElem* theElem;
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
printf("New redis context %p\n", c);
redisLibevAttach(EV_DEFAULT_ c);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
while (true)
{
if (c && c->err == 0)
{
theElem = NULL;
theTask = NULL;
theElem = fTaskQueue.DeQueue();
if (theElem != NULL)
theTask = (RedisTask*)theElem->GetEnclosingObject();
if (theTask)
{
redisAsyncCommand(c, GenericCallback, (void*)theTask, theTask->GetCmd());
}
else
OSThread::Sleep(kMinWaitTimeInMilSecs); // Is this necessary?
ev_loop(EV_DEFAULT_ EVLOOP_NONBLOCK);
}
else
{
printf("redis connection broken, reconnect...\n");
if (c)
{
printf("Free redis context %p\n", c);
redisAsyncFree(c);
}
c = redisAsyncConnect("127.0.0.1", 6379);
redisLibevAttach(EV_DEFAULT_ c);
redisAsyncSetConnectCallback(c,connectCallback);
redisAsyncSetDisconnectCallback(c,disconnectCallback);
}
}
调用redisAsyncFree时出错。回溯是这样的:
#0 0x00110402 in __kernel_vsyscall ()
#1 0x0026bc00 in raise () from /lib/libc.so.6
#2 0x0026d451 in abort () from /lib/libc.so.6
#3 0x002a121b in __libc_message () from /lib/libc.so.6
#4 0x002ac6fb in free () from /lib/libc.so.6
#5 0x081287fd in _dictClear () at OSRef.h:75
#6 0x0812881d in dictRelease () at OSRef.h:75
#7 0x08129475 in __redisAsyncFree () at OSRef.h:75
#8 0x08129839 in redisAsyncFree () at OSRef.h:75
#9 0x0812d711 in RedisThread::Entry (this=0x8385aa0)
我想知道我的错误处理逻辑是否不正确。那么,问题是,对于循环中 c->err 非零的情况,正确的逻辑是什么?如何清理并重新连接到服务器?
最佳答案
如果有帮助,我写了一个简单的类来处理自动重新连接。它不使用异步连接,但可能会配备它。
class Redis {
char *host;
int port;
public:
redisContext *c;
redisReply *r;
Redis(char* host, int port){
this->host = host;
this->port = port;
}
void connect(){
struct timeval timeout = { 1, 500000 };
if (this->c){
redisFree(this->c);
}
this->c = redisConnectWithTimeout(this->host, this->port, timeout);
if (this->c->err){
printf("Connection error: %s\n", this->c->errstr);
exit(1);
}
}
void cmd(char* r_cmd, int save_reply=0){
int retry = 0;
while(true){
this->r = (redisReply*)redisCommand(this->c, r_cmd);
if (this->r == NULL) {
fprintf(stdout, "Retrying to connect to redis...\n");
sleep(2);
this->connect();
} else {
if (!save_reply){
freeReplyObject(this->r);
}
return;
}
if (retry >= 10){
printf("Reply was null! (%s)\n",r_cmd);
exit(1);
}
retry++;
}
}
};
关于c++ - hiredis客户端,连接断开时redisAsyncFree报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9475488/
我是一名优秀的程序员,十分优秀!