クライアント側のタイムアウトを設定する (Valkey と Redis OSS) - Amazon ElastiCache

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

クライアント側のタイムアウトを設定する (Valkey と Redis OSS)

クライアント側のタイムアウトの設定

サーバーがリクエストを処理してレスポンスを生成するのに十分な時間を確保できるように、クライアント側のタイムアウトを適切に設定します。また、これにより、サーバーへの接続を確立できない場合でも、フェイルファストが可能です。特定の 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(); } } }