

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 設定用戶端逾時 (Valkey 和 Redis OSS)
<a name="BestPractices.Clients.Redis.ClientTimeout"></a>

**設定用戶端逾時**

適當地設定用戶端逾時，讓伺服器有足夠的時間來處理請求並產生回應。此外還能在無法建立伺服器連線時，讓伺服器快速檢錯。某些 Valkey 或 Redis OSS 命令可能比其他命令更昂貴。例如，包含多個必須以原子方式執行之命令的 Lua 指令碼或 MULTI/EXEC 交易。一般而言，建議設定較長的用戶端逾時，以避免用戶端還未收到來自伺服器的回應就已逾時，包括下列情況：
+ 在多個索引鍵之間執行命令
+ 執行包含多個個別 Valkey 或 Redis OSS 命令的 MULTI/EXEC 交易或 Lua 指令碼
+ 讀取較大的值
+ 執行如 BLPOP 等封鎖操作

若是 BLPOP 這類封鎖操作，最佳實務是將命令逾時設定為低於通訊端逾時的數字。

下列程式碼範例將示範以 redis-py、PHPRedis 和 Lettuce 實作用戶端逾時。

**逾時組態範例 1：redis-py**

下列程式碼範例使用 redis-py：

```
# connect to Redis server with a 100 millisecond timeout
# give every Redis command a 2 second timeout
client = redis.Redis(connection_pool=redis.BlockingConnectionPool(host=HOST, max_connections=10,socket_connect_timeout=0.1,socket_timeout=2))

res = client.set("key", "value") # will timeout after 2 seconds
print(res)                       # if there is a connection error

res = client.blpop("list", timeout=1) # will timeout after 1 second
                                      # less than the 2 second socket timeout
print(res)
```

**逾時組態範例 2：PHPRedis**

下列程式碼範例使用 PHPRedis：

```
// connect to Redis server with a 100ms timeout
// give every Redis command a 2s timeout
$client = new Redis();
$timeout = 0.1; // 100 millisecond connection timeout
$retry_interval = 100; // 100 millisecond retry interval
$client = new Redis();
if($client->pconnect($HOST, $PORT, 0.1, NULL, 100, $read_timeout=2) != TRUE){
	return; // ERROR: connection failed
}
$client->set($key, $value);

$res = $client->set("key", "value"); // will timeout after 2 seconds
print "$res\n";                      // if there is a connection error

$res = $client->blpop("list", 1); // will timeout after 1 second
print "$res\n";                   // less than the 2 second socket timeout
```

**逾時組態範例 3：Lettuce**

下列程式碼範例使用 Lettuce：

```
// connect to Redis server and give every command a 2 second timeout
public static void main(String[] args)
{
	RedisClient client = null;
	StatefulRedisConnection<String, String> connection = null;
	try {
		client = RedisClient.create(RedisURI.create(HOST, PORT));
		client.setOptions(ClientOptions.builder()
	.socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(100)).build()) // 100 millisecond connection timeout
	.timeoutOptions(TimeoutOptions.builder().fixedTimeout(Duration.ofSeconds(2)).build()) // 2 second command timeout 
	.build());

		// use the connection pool from above example

		commands.set("key", "value"); // will timeout after 2 seconds
		commands.blpop(1, "list"); // BLPOP with 1 second timeout
	} finally {
		if (connection != null) {
			connection.close();
		}

		if (client != null){
			client.shutdown();
		}
	}
}
```