hredis可以设置操作超时时间(在调用操作命令前调用redisSetTimeout),操作超时即返回;
redisContext *c;
redisReply *reply;
ssize_t s;
const char *cmd = "DEBUG SLEEP 3\r\n";
struct timeval tv;
c = connect(config);
test("Successfully completes a command when the timeout is not exceeded: ");
reply = redisCommand(c,"SET foo fast");
freeReplyObject(reply);
tv.tv_sec = 0;
tv.tv_usec = 10000;
redisSetTimeout(c, tv);
reply = redisCommand(c, "GET foo");
test_cond(reply != NULL && reply->type == REDIS_REPLY_STRING && memcmp(reply->str, "fast", 4) == 0);
freeReplyObject(reply);
disconnect(c, 0);
c = connect(config);
test("Does not return a reply when the command times out: ");
s = write(c->fd, cmd, strlen(cmd));
tv.tv_sec = 0;
tv.tv_usec = 10000;
redisSetTimeout(c, tv);
reply = redisCommand(c, "GET foo");
test_cond(s > 0 && reply == NULL && c->err == REDIS_ERR_IO && strcmp(c->errstr, "Resource temporarily unavailable") == 0);
freeReplyObject(reply);
详细可参看hredis的例子http://download.redis.io/redis-stable/deps/hiredis/test.c

本文深入探讨了hredis库中设置操作超时时间的方法及其实际应用效果。通过具体示例,验证了当操作未超出设定时间时,命令能够成功执行并返回预期结果;而当操作超时时,将不再返回回复,并抛出资源暂时不可用的错误。
3135

被折叠的 条评论
为什么被折叠?



