

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 配置客户端超时（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();
		}
	}
}
```