4

连接服务器的简单脚本:

#include "hiredis.h"
int main(void) {
    int fd;

    unsigned int j;
    redisReply *reply;
    reply = redisConnect(&fd, "test.com", 6379);

    if (reply != NULL) {
        printf("Connection error: %s", reply->reply);
        exit(1);
    }

    reply = redisCommand(fd,"PING");
    printf("PONG: %s\n", reply->reply);
    freeReplyObject(reply);
}

如果服务器可用- 一切正常。如果没有 - 有很长的停顿。例如,如何将等待时间减少到 2 秒?

4

2 回答 2

1

我对redis了解不多。但我假设,redisConnect 内部基本上也只是在阻塞 fd 上调用 connect()。

所以尝试使用setsockopt预先设置超时:

struct timeval timeout;
timeout.tv_usec = 0;
timeout.tv_sec = 2;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (void *)&timeout, sizeof(timeout));

这将发送超时设置为 2 秒,对于接收,您基本上也这样做。

干杯,

于 2010-11-29T06:38:24.400 回答
1

You'll need to modify the hiredis library, and the anetTcpGenericConnect function to make connect timeout aware. There's an example here of how to do it.

于 2010-09-28T22:02:39.843 回答