2010-09-28 58 views
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秒?

回答

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)); 

這臺發送timout到2秒,用於接收,你基本上做的是一樣的。

歡呼聲,