設定用戶端逾時 (Valkey 和 RedisOSS) - Amazon ElastiCache

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

設定用戶端逾時 (Valkey 和 RedisOSS)

設定用戶端逾時

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

  • 在多個索引鍵之間執行命令

  • 執行 MULTI/EXEC 交易或包含多個個別 Valkey 或 Redis OSS命令的 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(); } } }