All Products
Search
Document Center

Tair (Redis® OSS-Compatible):Use a client to connect to an instance

Last Updated:Nov 06, 2024

Tair (Redis OSS-compatible) instances are fully compatible with open source Redis. You can connect to Tair instances in the same manner as you connect to Redis databases. Therefore, you can use any Redis-compliant client to connect to a Tair instance.

Prerequisites

The operations listed in the following table are performed based on the type of the host on which the client is deployed.

Host

Operation

ECS instance (recommended)

  1. Make sure that the Elastic Compute Service (ECS) instance and the Tair instance belong to the same virtual private cloud (VPC). If the VPC IDs of these two instances are the same, the instances belong to the same VPC.

    Note
  2. Obtain the internal IP address of the ECS instance. For more information, see Network FAQ.

  3. Add the internal IP address of the ECS instance to a whitelist of the Tair instance. For more information, see Configure whitelists.

On-premises device

  1. By default, only internal endpoints are available for Tair instances. If you want to connect to a Tair instance over the Internet, you must apply for a public endpoint. For more information, see Apply for a public endpoint for an instance.

  2. The method used to obtain the public IP address of an on-premises device may vary based on your network environment or operation. The following list provides reference methods for obtaining the public IP address of an on-premises device by using commands in different operating systems:

    • Linux: Open the CLI, enter the curl ifconfig.me command, and then press the Enter key.

    • Windows: Open Command Prompt, enter the curl ip.me command, and then press the Enter key.

    • macOS: Start Terminal, enter the curl ifconfig.me command, and then press the Enter key.

  3. Add the public IP address of your on-premises device to a whitelist of the Tair instance. For more information, see Configure whitelists.

Usage notes

  • By default, cluster and read/write splitting instances run in proxy mode. In this mode, you can connect to such an instance by using the endpoint of a proxy node in the instance in the same manner as you connect to a standard instance. For more information about cluster and read/write splitting instances, see Cluster master-replica instances and Read/write splitting instances.

    Note

    If you use a private endpoint to connect to a cluster instance, you can connect to the instance in the same manner as you connect to an open source Redis cluster. For more information about private endpoints, see Enable the direct connection mode.

  • If password-free access is enabled for a Tair instance deployed in a VPC, clients that are located in the same VPC as the instance can connect to the instance without using passwords. For more information, see Enable password-free access.

Obtain connection information

When you use a client to connect to a Tair or Redis Open-Source Edition instance, you must obtain the connection information described in the following table and specify the information in the code.

Item

Description

Instance endpoint

Tair instances support multiple endpoint types. We recommend that you use VPC endpoints for higher security and lower network latency. For more information, see View endpoints.

Port number

Use the default port number 6379 or specify a custom port number. For more information, see Change the endpoint or port number of an instance.

Instance account (optional for specific clients)

By default, a Tair instance has a database account that is named after the instance ID. Example: r-bp10noxlhcoim2****. You can create another database account and grant the required permissions to the account. For more information, see Create and manage database accounts.

Password

The password format varies based on the selected account:

  • If you use the default account whose username is the same as the instance ID, enter the password.

  • If you use a custom account, enter the password in the <user>:<password> format. For example, if the username of the custom account is testaccount and the password is Rp829dlwa, enter testaccount:Rp829dlwa as the password.

Note
  • If you use a third-party database management tool such as Remote Desktop Manager (RDM) to connect to a Tair instance, enter the password in the user:password format.

  • If you forget your password, you can reset it. For more information, see Change or reset the password.

Common types of clients

For a list of the clients supported by Tair and Redis Open-Source Edition, see Redis Clients.

Important

This section provides only sample code on how to use common clients to connect to Tair.

Jedis

The following sample project is created by using Maven. You can also manually download the Jedis client.

  1. Open the compiler and create a project.

  2. Add the following dependency to the pom file.

    In this example, Jedis 4.3.0 is used.

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  3. Enter the following code in the editor and modify the code based on the comments:

    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();
            // Specify the maximum number of idle connections based on your business needs. This value cannot exceed the maximum number of connections supported by the Tair instance. 
            config.setMaxIdle(200);
            // Specify the maximum number of connections based on your business needs. This value cannot exceed the maximum number of connections supported by the Tair instance. 
            config.setMaxTotal(300);
            config.setTestOnBorrow(false);
            config.setTestOnReturn(false);
            // Replace the values of the host and password parameters with the endpoint of the Tair instance and the password of the instance account. 
            String host = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com";
            String password = "r-bp1s1bt2tlq3p1****:Database123";
            JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                // Refer to the following example to perform related operations: 
                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) {
                // Handle timeout errors or other exceptions. 
                e.printStackTrace();
            }
            finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
            pool.destroy();    // If your application exits and you want to destroy the resources, call this method. Then, the connection is closed, and the resources are released. 
        }
    }
  4. Run the preceding code. The following output is expected on successful completion:

    bar
    [bike, car]
    Important

    If specific parameters are improperly configured or some features are improperly used, errors may occur. For more information about how to troubleshoot the errors, see Common errors and troubleshooting.

PhpRedis

  1. Download and install the PhpRedis client.

  2. Enter the following code in the PHP editor and modify the code based on the comments.

    In this example, PHP 8.2.1 and PhpRedis 5.3.7 are used.

    <?php
     /* Replace the values of the host and port parameters with the endpoint and port number of the instance.   */
     $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
     $port = 6379;
     /* Replace the values of the user and pwd parameters with the username and password of the instance account. */
     $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());
      }
      /* You can perform operations on the instance after the connection is established. The following code provides an example on how to call the set and get methods:   */
     if ($redis->set("foo", "bar") == false) {
             die($redis->getLastError());
     }
     $value = $redis->get("foo");
     echo $value;
     ?>
  3. Run the preceding code to connect to the instance.

    Note

    Common errors and solutions:

redis-py

  1. Download and install the redis-py client.

  2. Enter the following code in the Python editor and modify the code based on the comments.

    In this example, Python 3.9 and redis-py 4.4.1 are used.

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    import redis
    # Replace the values of the host and port parameters with the endpoint and port number of the instance. 
    host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    # Replace the value of the pwd parameter with the password of the instance account. 
    pwd = 'testaccount:Rp829dlwa'
    r = redis.Redis(host=host, port=port, password=pwd)
    # You can perform operations on the instance after the connection is established. The following code provides an example on how to call the set and get methods: 
    r.set('foo', 'bar')
    print(r.get('foo'))
  3. Run the preceding code to connect to the instance.

Spring Data Redis

The following sample project is created by using Maven. You can also manually download the Lettuce or Jedis client.

  1. Open the compiler and create a project.

  2. Add the following dependencies to the pom file and download the Lettuce or Jedis client. We recommend that you do not use a Lettuce version earlier than 6.3.0.

    <?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>
  3. Enter the following code in the Spring Data Redis editor and modify the code based on the comments.

    In this example, Spring Data Redis 2.4.2 is used.

    • Spring Data Redis With Jedis

      @Bean
           JedisConnectionFactory redisConnectionFactory() {
               RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", port);
       
               JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
               // Specify the maximum number of connections based on your business needs. This value cannot exceed the maximum number of connections supported by the Tair instance. 
               jedisPoolConfig.setMaxTotal(30);
               // Specify the maximum number of idle connections based on your business needs. This value cannot exceed the maximum number of connections supported by the Tair instance. 
               jedisPoolConfig.setMaxIdle(20);
               // Disable testOn[Borrow|Return] to prevent additional PING commands from being generated. 
               jedisPoolConfig.setTestOnBorrow(false);
               jedisPoolConfig.setTestOnReturn(false);
       
               JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling().poolConfig(
                   jedisPoolConfig).build();
       
               return new JedisConnectionFactory(config, jedisClientConfiguration);
           }
    • Spring Data Redis With Lettuce 

      @Configuration
      public class BeanConfig {
          /**
           * Enable TCP keepalive and configure the following three parameters:
           *  TCP_KEEPIDLE = 30
           *  TCP_KEEPINTVL = 10
           *  TCP_KEEPCNT = 3
           */
          private static final int TCP_KEEPALIVE_IDLE = 30;
      
          /**
           * The TCP_USER_TIMEOUT parameter can avoid situations where Lettuce remains stuck in a continuous timeout loop during a failure or crash event. 
           * refer: 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");
      
              // Config 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;
          }
      }
  4. Run the preceding code to connect to the Tair instance.

C or C++ client

  1. Download and install hiredis.

  2. Enter the following code in the C or C ++ editor and modify the code based on the comments.

    In this example, hiredis 1.1.0 is used.

    #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 server */
        reply = redisCommand(c,"PING");
        printf("PING: %s\n", reply->str);
        freeReplyObject(reply);
        /* Set a key */
        reply = redisCommand(c,"SET %s %s", "foo", "hello world");
        printf("SET: %s\n", reply->str);
        freeReplyObject(reply);
        /* Set a key using binary safe 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);
        /* Try a GET and two INCR */
        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);
        /* again ... */
        reply = redisCommand(c,"INCR counter");
        printf("INCR counter: %lld\n", reply->integer);
        freeReplyObject(reply);
        /* Create a list of numbers, from 0 to 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);
            }
        /* Let's check what we have inside the list */
        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);
        /* Disconnects and frees the context */
        redisFree(c);
        return 0;
    }
  3. Compile the code.

    gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. Perform a test run and connect to the instance.

     example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 r-bp10noxlhcoim2**** password

.NET

  1. Download and install StackExchange.Redis 2.7.20 or later. For more information, see Notice on update of StackExchange.Redis.

    Important

    We recommend that you do not use the ServiceStack Redis or CSRedis client.

    • If you use ServiceStack Redis and run into issues related to the client, you must purchase technical support from ServiceStack.

    • The support for the CSRedis client has been ended.

  2. Enter the following code in the StackExchange.Redis editor and modify the code based on the comments.

    In this example, StackExchange.Redis 2.7.20 is used.

    using StackExchange.Redis;
     // Specify the endpoint, port number, and password of the instance. 
     private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,password=testaccount:Rp829dlwa,connectTimeout=2000");
      //the lock for singleton
     private static readonly object Locker = new object();
      //singleton
     private static ConnectionMultiplexer redisConn;
     //singleton
     public static ConnectionMultiplexer getRedisConn()
     {
         if (redisConn == null)
         {
             lock (Locker)
             {
                 if (redisConn == null || !redisConn.IsConnected)
                 {
                     redisConn = ConnectionMultiplexer.Connect(configurationOptions);
                 }
             }
         }
         return redisConn;
     }
    Note
    • ConfigurationOptions is a core object of the StackExchange.Redis client. ConfigurationOptions is shared and reused by the client. The singleton pattern is recommended. For more information about parameter settings, see Configuration Options.

    • GetDatabase() returns a lightweight object. You can obtain this object from the ConnectionMultiplexer object.

       redisConn = getRedisConn();
       var db = redisConn.GetDatabase();
  3. Use the client to perform operations on common data structures. Examples:

    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

  1. Download and install the node-redis client.

  2. Enter the following code in the node-redis client and modify the code based on the comments.

    In this example, Node.js 19.4.0 and node-redis 4.5.1 are used.

    import { createClient } from 'redis';
    
    // Specify the port number, endpoint, username, and password of the instance.
    const client = createClient({
      // redis[s]://[[username][:password]@][host][:port][/db-number]
      url: 'redis://testaccount:Rp829dlwa@r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379'
    });
    
    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();
    Note

    If the SyntaxError: Cannot use import statement outside a module error message is returned, change the suffix of the .js file to .mjs and add the --experimental-modules option when you use this client. Example: node --experimental-modules redis.mjs.

  3. Run the preceding code to connect to the instance.

go-redis

  1. Download and install the go-redis client.

  2. Enter the following code in the go-redis client and modify the code based on the comments.

    In this example, Go 1.18.5 and go-redis 8.11.5 are used.

    package main
    
    import (
    	"github.com/go-redis/redis"
    	"fmt"
    )
    
    func ExampleClient() {
    	client := redis.NewClient(&redis.Options{
            // Specify the endpoint and port number of the instance.
    		Addr:     "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
            // Specify the password of the instance account.
    		Password: "testaccount:Rp829dlwa",
    		DB:       0,  // use default DB
    	})
        // The following code provides an example on how to call the set and get methods: 
    	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()
    }
  3. Run the preceding code to connect to the instance.

Lettuce

The following sample project is created by using Maven. You can also manually download the Lettuce client.

  1. Open the compiler and create a project.

  2. Add the following dependencies to the pom file and download Lettuce 6.3.0. We recommend that you do not use a Lettuce version earlier than 6.3.0.

    In this example, Lettuce 6.3.0 is used.

    <<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>
  3. Enter the following code in the editor and modify the code based on the comments:

    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 {
        /**
         * Enable TCP keepalive and configure the following three parameters:
         *  TCP_KEEPIDLE = 30
         *  TCP_KEEPINTVL = 10
         *  TCP_KEEPCNT = 3
         */
        private static final int TCP_KEEPALIVE_IDLE = 30;
    
        /**
         * The TCP_USER_TIMEOUT parameter can avoid situations where Lettuce remains stuck in a continuous timeout loop during a failure or crash event. 
         * refer: 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) {
            // Replace the values of host, user, password, and port with the actual instance information. 
            String host = "r-bp1s1bt2tlq3p1****.redis.rds.aliyuncs.com";
            String user = "r-bp1s1bt2tlq3p1****";
            String password = "Da****3";
            int port = 6379;
    
            // Config RedisURL
            RedisURI uri = RedisURI.Builder
                    .redis(host, port)
                    .withAuthentication(user, password)
                    .build();
    
            // Config 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"));
    
            // If your application exits and you want to destroy the resources, call this method. Then, the connection is closed, and the resources are released. 
            connection.close();
            client.shutdown();
        }
    }
  4. Run the preceding code. The following output is expected on successful completion:

    OK
    bar