Tair (Redis OSS-compatible) インスタンスは、オープンソースの Redis と完全に互換性があります。Redis データベースに接続するのと同じ方法で、Redis 準拠のクライアントを使用して Tair インスタンスに接続できます。
前提条件
クライアントがデプロイされている場所に基づいて、次の操作を完了します。
クライアントのデプロイ場所 | 完了すべき操作 |
ECS インスタンス (推奨) |
|
ローカル |
|
注意
インスタンスがクラスターアーキテクチャまたは読み書き分離アーキテクチャを使用している場合、デフォルトでプロキシノードのエンドポイントが提供されます。標準アーキテクチャのインスタンスに接続するのと同じ方法でインスタンスに接続できます。
説明直接接続エンドポイントを使用してクラスターインスタンスに接続する場合、接続方法はオープンソースの Redis クラスターへの接続と同じです。
インスタンスでVPC 経由のパスワードなしのアクセスが有効になっている場合、同じ VPC 内のクライアントはパスワードなしでインスタンスに接続できます。
接続情報の取得
クライアントを使用して Tair (または Redis Community Edition) インスタンスに接続する場合、次の情報を取得してコードに設定する必要があります。
取得する情報 | 取得方法 |
インスタンスのエンドポイント | インスタンスページに移動し、上部のナビゲーションバーでリージョンを選択し、ターゲットインスタンスの ID をクリックします。 [接続情報] セクションで、さまざまな接続タイプのエンドポイントとポートを表示できます。 説明 インスタンスは複数のエンドポイントタイプをサポートしています。セキュリティを強化し、ネットワーク遅延を低減するために、VPC エンドポイントを使用することをお勧めします。詳細については、「エンドポイントの表示」をご参照ください。 |
ポート | デフォルトのポートは 6379 です。ポートをカスタマイズすることもできます。詳細については、「エンドポイントまたはポートの変更」をご参照ください。 |
インスタンスのアカウント (一部のクライアントでは不要) | デフォルトでは、インスタンスには r-bp10noxlhcoim2**** のようにインスタンス ID にちなんで名付けられたアカウントがあります。新しいアカウントを作成して権限を付与することもできます。詳細については、「アカウントの作成と管理」をご参照ください。 |
アカウントのパスワード | パスワードのフォーマットは、選択したアカウントによって異なります:
説明
|
一般的なクライアントの例
Tair (および Redis Community Edition) がサポートするクライアントのリストについては、「Redis クライアント」をご参照ください。
このセクションでは、一般的なクライアントを使用して Tair に接続する方法のサンプルコードのみを提供します。
Jedis
この例では、Maven を使用してプロジェクトを作成します。Jedis クライアントを手動でダウンロードすることもできます。
コンパイラを開き、プロジェクトを作成します。
次のコードを
pom.xmlファイルに追加します。この例では Jedis 4.3.0 を使用します。
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency>エディターに次のコードを入力し、コメントに基づいてコードを修正します。
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisExample { public static void main(String[] args) { JedisPoolConfig config = new JedisPoolConfig(); // アイドル接続の最大数。必要に応じてこの値を評価してください。この値は、Tair インスタンスでサポートされている最大接続数を超えることはできません。 config.setMaxIdle(200); // 最大接続数。必要に応じてこの値を評価してください。この値は、Tair インスタンスでサポートされている最大接続数を超えることはできません。 config.setMaxTotal(300); config.setTestOnBorrow(false); config.setTestOnReturn(false); // host および password パラメーターの値を、インスタンスのエンドポイントとパスワードに置き換えます。 String host = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com"; // デフォルトアカウントの場合、パスワードを直接入力できます。新しく作成されたアカウントの場合、パスワードは アカウント:パスワード の形式である必要があります。たとえば、新しいアカウントが testaccount で、パスワードが Rp829dlwa の場合、testaccount:Rp829dlwa と入力します。 String password = "r-bp1s1bt2tlq3p1****:Database123"; JedisPool pool = new JedisPool(config, host, 6379, 3000, password); Jedis jedis = null; try { jedis = pool.getResource(); // 操作を実行します。次のコードは例です。 jedis.set("foo10", "bar"); System.out.println(jedis.get("foo10")); jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); System.out.println(jedis.zrange("sose", 0, -1)); } catch (Exception e) { // タイムアウトまたはその他の例外を処理します。 e.printStackTrace(); } finally { if (jedis != null) { jedis.close(); } } pool.destroy(); // アプリケーションが終了し、リソースを破棄する必要がある場合は、このメソッドを呼び出します。このメソッドは接続を切断し、リソースを解放します。 } }プロジェクトを実行します。次の出力が期待されます:
bar [bike, car]重要Jedis を使用する場合、無効なパラメーターを設定したり、一部の機能を不適切な方法で使用したりすると、エラーが発生する可能性があります。これらのエラーのトラブルシューティングについては、「」および「一般的なエラー」をご参照ください。
PhpRedis
PhpRedis クライアントをダウンロードしてインストールします。
PHP エディターに次のコードを入力し、コメントに基づいてコードを修正します。
この例では PHP 8.2.1 と PhpRedis 5.3.7 を使用します。
<?php /* host および port パラメーターの値を、インスタンスのエンドポイントとポートに置き換えます。 */ $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com"; $port = 6379; /* user および pwd パラメーターの値を、インスタンスのアカウントとパスワードに置き換えます。 */ $user = "testaccount"; $pwd = "Rp829dlwa"; $redis = new Redis(); if ($redis->connect($host, $port) == false) { die($redis->getLastError()); } if ($redis->auth([$user, $pwd]) == false) { die($redis->getLastError()); } /* 認証が完了したら、データベース操作を実行できます。次のコードは、SET と GET の使用例です。 */ if ($redis->set("foo", "bar") == false) { die($redis->getLastError()); } $value = $redis->get("foo"); echo $value; ?>コードを実行します。
説明一般的なエラーと解決策:
Cannot assign requested address: このエラーの原因と解決策については、「「Cannot assign requested address」エラーが報告される」をご参照ください。redis protocol error, got ' ' as reply type byte: PhpRedis クライアントをアップグレードしてください。詳細については、「phpredis/phpredis#1585」をご参照ください。
redis-py
redis-py クライアントをダウンロードしてインストールします。
Python エディターに次のコードを入力し、コメントに基づいてコードを修正します。
この例では Python 3.9 と redis-py 4.4.1 を使用します。
#!/usr/bin/env python #-*- coding: utf-8 -*- import redis # host および port パラメーターの値を、インスタンスのエンドポイントとポートに置き換えます。 host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com' port = 6379 # pwd パラメーターの値を、インスタンスのパスワードに置き換えます。 # デフォルトアカウントの場合、パスワードを直接入力できます。新しく作成されたアカウントの場合、パスワードは アカウント:パスワード の形式である必要があります。たとえば、新しいアカウントが testaccount で、パスワードが Rp829dlwa の場合、testaccount:Rp829dlwa と入力します。 pwd = 'testaccount:Rp829dlwa' r = redis.Redis(host=host, port=port, password=pwd) # 接続が確立された後、データベース操作を実行できます。次のコードは、SET と GET の使用例です。 r.set('foo', 'bar') print(r.get('foo'))コードを実行します。
Spring Data Redis
この例では、Maven を使用してプロジェクトを作成します。Lettuce または Jedis クライアントを手動でダウンロードすることもできます。
コンパイラを開き、プロジェクトを作成します。
次のコードを
pomファイルに追加し、Lettuce または Jedis をダウンロードします。重要Lettuce を使用する場合、バージョン 6.3.0.RELEASE 以降を使用し、TCP_USER_TIMEOUT パラメーターを設定することをお勧めします。これにより、Lettuce クライアントでのブラックホールフィルタリングの問題を防ぐことができます。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.aliyun.tair</groupId> <artifactId>spring-boot-example</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-example</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>6.3.0.RELEASE</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-transport-native-epoll</artifactId> <version>4.1.100.Final</version> <classifier>linux-x86_64</classifier> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Spring Data Redis エディターに次のコードを入力し、コメントに基づいてコードを修正します。
この例では Spring Data Redis 2.4.2 を使用します。
Jedis を使用した Spring Data Redis
@Bean JedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", port); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 最大接続数。必要に応じてこのパラメーターを設定してください。この値は、インスタンスタイプでサポートされている最大接続数を超えることはできません。 jedisPoolConfig.setMaxTotal(30); // アイドル接続の最大数。必要に応じてこのパラメーターを設定してください。この値は、インスタンスタイプでサポートされている最大接続数を超えることはできません。 jedisPoolConfig.setMaxIdle(20); // 追加の PING コマンドが生成されないように、testOn[Borrow|Return] を無効にします。 jedisPoolConfig.setTestOnBorrow(false); jedisPoolConfig.setTestOnReturn(false); JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling().poolConfig( jedisPoolConfig).build(); return new JedisConnectionFactory(config, jedisClientConfiguration); }Lettuce を使用した Spring Data Redis (TCP_USER_TIMEOUT パラメーターの設定を含む)
@Configuration public class BeanConfig { /** * TCP_KEEPALIVE を有効にし、次の 3 つのパラメーターを設定します: * TCP_KEEPIDLE = 30 * TCP_KEEPINTVL = 10 * TCP_KEEPCNT = 3 */ private static final int TCP_KEEPALIVE_IDLE = 30; /** * TCP_USER_TIMEOUT パラメーターは、障害や故障が発生した場合に Lettuce が継続的にタイムアウトするのを防ぐことができます。 * 参照: https://github.com/lettuce-io/lettuce-core/issues/2082 */ private static final int TCP_USER_TIMEOUT = 30; @Bean LettuceConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName("r-bp1y4is8svonly****pd.redis.rds.aliyuncs.com"); config.setPort(6379); config.setUsername("r-bp1y4is8svonly****"); config.setPassword("Da****3"); // TCP KeepAlive の設定 SocketOptions socketOptions = SocketOptions.builder() .keepAlive(KeepAliveOptions.builder() .enable() .idle(Duration.ofSeconds(TCP_KEEPALIVE_IDLE)) .interval(Duration.ofSeconds(TCP_KEEPALIVE_IDLE / 3)) .count(3) .build()) .tcpUserTimeout(TcpUserTimeoutOptions.builder() .enable() .tcpUserTimeout(Duration.ofSeconds(TCP_USER_TIMEOUT)) .build()) .build(); LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder().clientOptions( ClientOptions.builder().socketOptions(socketOptions).build()).build(); return new LettuceConnectionFactory(config, lettuceClientConfiguration); } @Bean RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template; } }
コードを実行します。
C または C++
C クライアントをダウンロードしてインストールします。
C または C++ エディターに次のコードを入力し、コメントに基づいてコードを修正します。
この例では HiRedis 1.1.0 を使用します。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <hiredis.h> int main(int argc, char **argv) { unsigned int j; redisContext *c; redisReply *reply; if (argc < 4) { printf("Usage: example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 instance_id password\n"); exit(0); } const char *hostname = argv[1]; const int port = atoi(argv[2]); const char *instance_id = argv[3]; const char *password = argv[4]; struct timeval timeout = { 1, 500000 }; // 1.5 seconds c = redisConnectWithTimeout(hostname, port, timeout); if (c == NULL || c->err) { if (c) { printf("Connection error: %s\n", c->errstr); redisFree(c); } else { printf("Connection error: can't allocate redis context\n"); } exit(1); } /* AUTH */ reply = redisCommand(c, "AUTH %s", password); printf("AUTH: %s\n", reply->str); freeReplyObject(reply); /* PING サーバー */ reply = redisCommand(c,"PING"); printf("PING: %s\n", reply->str); freeReplyObject(reply); /* キーを設定 */ reply = redisCommand(c,"SET %s %s", "foo", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* バイナリセーフ API を使用してキーを設定 */ reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); printf("SET (binary API): %s\n", reply->str); freeReplyObject(reply); /* GET を 1 回、INCR を 2 回試行 */ reply = redisCommand(c,"GET foo"); printf("GET foo: %s\n", reply->str); freeReplyObject(reply); reply = redisCommand(c,"INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* 再度... */ reply = redisCommand(c,"INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* 0 から 9 までの数値のリストを作成 */ reply = redisCommand(c,"DEL mylist"); freeReplyObject(reply); for (j = 0; j < 10; j++) { char buf[64]; snprintf(buf,64,"%d",j); reply = redisCommand(c,"LPUSH mylist element-%s", buf); freeReplyObject(reply); } /* リストの中身を確認しましょう */ reply = redisCommand(c,"LRANGE mylist 0 -1"); if (reply->type == REDIS_REPLY_ARRAY) { for (j = 0; j < reply->elements; j++) { printf("%u) %s\n", j, reply->element[j]->str); } } freeReplyObject(reply); /* 接続を切断し、コンテキストを解放します */ redisFree(c); return 0; }コードをコンパイルします。
gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredisテストを実行して接続を確立します。
./example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 r-bp10noxlhcoim2**** password
.NET
バージョン 2.7.20 以降の StackExchange.Redis クライアントをダウンロードしてインストールします。詳細については、「StackExchange.Redis の更新に関する通知」をご参照ください。
重要ServiceStack Redis または CSRedis クライアントは使用しないことをお勧めします。
ServiceStack Redis を使用していてクライアントに関連する問題が発生した場合は、ServiceStack からテクニカルサポートを購入する必要があります。
CSRedis クライアントのサポートは終了しました。
StackExchange.Redis エディターに次のコードを入力し、コメントに基づいてコードを修正します。
この例では StackExchange.Redis 2.7.20 を使用します。
using StackExchange.Redis; // インスタンスのエンドポイント、ポート、パスワードを設定します。 private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,password=testaccount:Rp829dlwa,connectTimeout=2000"); // シングルトン用のロック private static readonly object Locker = new object(); // シングルトン private static ConnectionMultiplexer redisConn; // シングルトン public static ConnectionMultiplexer getRedisConn() { if (redisConn == null) { lock (Locker) { if (redisConn == null || !redisConn.IsConnected) { redisConn = ConnectionMultiplexer.Connect(configurationOptions); } } } return redisConn; }説明ConfigurationOptions は StackExchange.Redis のコアです。アプリケーション全体で共有および再利用されます。シングルトンとして設定する必要があります。パラメーターの詳細については、「ConfigurationOptions」をご参照ください。
GetDatabase()によって返されるオブジェクトは軽量です。使用するたびに ConnectionMultiplexer オブジェクトから取得できます。redisConn = getRedisConn(); var db = redisConn.GetDatabase();
クライアントを使用して、一般的なデータ構造に対する操作を実行します。例:
String
//set get string strKey = "hello"; string strValue = "world"; bool setResult = db.StringSet(strKey, strValue); Console.WriteLine("set " + strKey + " " + strValue + ", result is " + setResult); //incr string counterKey = "counter"; long counterValue = db.StringIncrement(counterKey); Console.WriteLine("incr " + counterKey + ", result is " + counterValue); //expire db.KeyExpire(strKey, new TimeSpan(0, 0, 5)); Thread.Sleep(5 * 1000); Console.WriteLine("expire " + strKey + ", after 5 seconds, value is " + db.StringGet(strKey)); //mset mget KeyValuePair<RedisKey, RedisValue> kv1 = new KeyValuePair<RedisKey, RedisValue>("key1", "value1"); KeyValuePair<RedisKey, RedisValue> kv2 = new KeyValuePair<RedisKey, RedisValue>("key2", "value2"); db.StringSet(new KeyValuePair<RedisKey, RedisValue>[] {kv1,kv2}); RedisValue[] values = db.StringGet(new RedisKey[] {kv1.Key, kv2.Key}); Console.WriteLine("mget " + kv1.Key.ToString() + " " + kv2.Key.ToString() + ", result is " + values[0] + "&&" + values[1]);Hash
string hashKey = "myhash"; //hset db.HashSet(hashKey,"f1","v1"); db.HashSet(hashKey,"f2", "v2"); HashEntry[] values = db.HashGetAll(hashKey); //hgetall Console.Write("hgetall " + hashKey + ", result is"); for (int i = 0; i < values.Length;i++) { HashEntry hashEntry = values[i]; Console.Write(" " + hashEntry.Name.ToString() + " " + hashEntry.Value.ToString()); } Console.WriteLine();List
//list key string listKey = "myList"; //rpush db.ListRightPush(listKey, "a"); db.ListRightPush(listKey, "b"); db.ListRightPush(listKey, "c"); //lrange RedisValue[] values = db.ListRange(listKey, 0, -1); Console.Write("lrange " + listKey + " 0 -1, result is "); for (int i = 0; i < values.Length; i++) { Console.Write(values[i] + " "); } Console.WriteLine();Set
//set key string setKey = "mySet"; //sadd db.SetAdd(setKey, "a"); db.SetAdd(setKey, "b"); db.SetAdd(setKey, "c"); //sismember bool isContains = db.SetContains(setKey, "a"); Console.WriteLine("set " + setKey + " contains a is " + isContains );Sorted Set
string sortedSetKey = "myZset"; //sadd db.SortedSetAdd(sortedSetKey, "xiaoming", 85); db.SortedSetAdd(sortedSetKey, "xiaohong", 100); db.SortedSetAdd(sortedSetKey, "xiaofei", 62); db.SortedSetAdd(sortedSetKey, "xiaotang", 73); //zrevrangebyscore RedisValue[] names = db.SortedSetRangeByRank(sortedSetKey, 0, 2, Order.Ascending); Console.Write("zrevrangebyscore " + sortedSetKey + " 0 2, result is "); for (int i = 0; i < names.Length; i++) { Console.Write(names[i] + " "); } Console.WriteLine();
node-redis
node-redis クライアントをダウンロードしてインストールします。
node-redis クライアントに次のコードを入力し、コメントに基づいてコードを修正します。
この例では Node.js 19.4.0 と node-redis 4.5.1 を使用します。
import { createClient } from 'redis'; // インスタンスのポート、エンドポイント、アカウント、パスワードを設定します。 const host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'; const port = 6379; const username = 'testaccount'; // パスワードに !@#$%^&*()+-=_ などの特殊文字が含まれている場合は、encodeURIComponent を使用してパスワードをエンコードすることをお勧めします。例: password = encodeURIComponent(password)。 const password = 'Rp829dlwa'; const client = createClient({ // redis://[[username]:[password]@[host][:port]/[db-number] url: `redis://${username}:${password}@${host}:${port}/0` }); client.on('error', (err) => console.log('Redis Client Error', err)); await client.connect(); await client.set('foo', 'bar'); const value = await client.get('foo'); console.log("get foo: %s", value); await client.disconnect();説明SyntaxError: Cannot use import statement outside a moduleエラーメッセージが報告された場合は、ファイル拡張子を.jsから.mjsに変更し、呼び出し時に--experimental-modulesオプションを追加します。例:node --experimental-modules redis.mjs。コードを実行します。
go-redis
go-redis クライアントをダウンロードしてインストールします。
go-redis エディターに次のコードを入力し、コメントに基づいてコードを修正します。
この例では Go 1.18.5 と go-redis 8.11.5 を使用します。
package main import ( "github.com/go-redis/redis" "fmt" ) func ExampleClient() { client := redis.NewClient(&redis.Options{ // プレースホルダーをインスタンスのエンドポイントとポートに置き換えます。 Addr: "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379", // プレースホルダーをインスタンスのパスワードに置き換えます。 Password: "testaccount:Rp829dlwa", DB: 0, // use default DB }) // 次のコードは、SET と GET の使用例です。 err := client.Set("foo", "bar", 0).Err() if err != nil { panic(err) } val, err := client.Get("foo").Result() if err != nil { panic(err) } fmt.Println("set : foo -> ", val) } func main() { ExampleClient() }コードを実行します。
Lettuce
次のサンプルプロジェクトは Maven を使用して作成されます。Lettuce クライアントを手動でダウンロードすることもできます。
コンパイラを開き、プロジェクトを作成します。
次の依存関係を
pom.xmlファイルに追加し、Lettuce 6.3.0 をダウンロードします。6.3.0 より前のバージョンの Lettuce は使用しないことをお勧めします。この例では、Lettuce 6.3.0 を使用します。
<<dependencies> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>6.3.0.RELEASE</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-transport-native-epoll</artifactId> <version>4.1.100.Final</version> <classifier>linux-x86_64</classifier> </dependency> </dependencies>エディターに次のコードを入力し、コメントに基づいてコードを修正します:
import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.SocketOptions; import io.lettuce.core.SocketOptions.KeepAliveOptions; import io.lettuce.core.SocketOptions.TcpUserTimeoutOptions; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import java.time.Duration; public class LettuceExample { /** * TCP keepalive を有効にし、次の 3 つのパラメーターを設定します: * TCP_KEEPIDLE = 30 * TCP_KEEPINTVL = 10 * TCP_KEEPCNT = 3 */ private static final int TCP_KEEPALIVE_IDLE = 30; /** * TCP_USER_TIMEOUT パラメーターは、障害やクラッシュイベント中に Lettuce が継続的なタイムアウトループでスタックする状況を回避できます。 * 参照: https://github.com/lettuce-io/lettuce-core/issues/2082 */ private static final int TCP_USER_TIMEOUT = 30; private static RedisClient client = null; private static StatefulRedisConnection<String, String> connection = null; public static void main(String[] args) { // host、user、password、port の値を実際のインスタンス情報に置き換えます。 String host = "r-bp1s1bt2tlq3p1****.redis.rds.aliyuncs.com"; String user = "r-bp1s1bt2tlq3p1****"; String password = "Da****3"; int port = 6379; // RedisURI の設定 RedisURI uri = RedisURI.Builder .redis(host, port) .withAuthentication(user, password) .build(); // TCP KeepAlive の設定 SocketOptions socketOptions = SocketOptions.builder() .keepAlive(KeepAliveOptions.builder() .enable() .idle(Duration.ofSeconds(TCP_KEEPALIVE_IDLE)) .interval(Duration.ofSeconds(TCP_KEEPALIVE_IDLE/3)) .count(3) .build()) .tcpUserTimeout(TcpUserTimeoutOptions.builder() .enable() .tcpUserTimeout(Duration.ofSeconds(TCP_USER_TIMEOUT)) .build()) .build(); client = RedisClient.create(uri); client.setOptions(ClientOptions.builder() .socketOptions(socketOptions) .build()); connection = client.connect(); RedisCommands<String, String> commands = connection.sync(); System.out.println(commands.set("foo", "bar")); System.out.println(commands.get("foo")); // アプリケーションが終了し、リソースを破棄する場合は、このメソッドを呼び出します。その後、接続が閉じられ、リソースが解放されます。 connection.close(); client.shutdown(); } }上記のコードを実行します。正常に完了すると、次の出力が期待されます:
OK bar