All Products
Search
Document Center

:Use a client to connect to a Tair instance

Last Updated:Mar 22, 2024

Tair is fully compatible with open source Redis. You can connect to Tair in the same manner as you connect to open source Redis. 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 are deployed in the same virtual private cloud (VPC). The basic information sections of the instances must display the same VPC ID. If the instances are deployed in different VPCs, you can change the VPC to which the ECS instance belongs. For more information, see Change the VPC of an ECS instance.

  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 a Tair 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 Enter.

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

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

  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 a Tair 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 architecture and Read/write splitting architecture.

    Note

    If you use a private endpoint to connect to a Tair 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 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 VPCs for higher security and lower network latency. For more information, see View endpoints and port numbers.

Port number

The default port number is 6379. You can also use a custom port number. For more information, see Change the endpoint or port of a Tair 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, directly enter the password.

  • If you use a custom account, enter the password in the <user>:<password> format. A password in this format can also be used for default account logon. 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 management tool such as Redis Desktop Manager (RDM) to connect to the Tair instance, enter the password in the <user>:<password> format.

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

Sample code for common clients

Tair supports all clients that are supported by open source Redis. For more information, see Connect with Redis clients. This section provides sample code on how to use common clients to connect to Tair.

TairJedis

TairJedis is a dedicated client for Tair that is developed by Alibaba Cloud based on Jedis. TairJedis not only provides all the features offered by Jedis but also includes additional functionalities to support the extended data structures of Tair. For more information, visit GitHub.

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 solutions.

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 Tair 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 use the TairString data module:  */
     if ($redis->set("foo", "bar") == false) {
             die($redis->getLastError());
     }
     /* Returns: 1 */
     $redis->rawCommand("CAS", "foo", "bar", "bzz");
     /* Returns: 1 */
     $redis->rawCommand("CAD", "foo", "bzz");
     /* Returns: OK */
     $redis->rawCommand("EXSET", "foo", "200", "VER", "1");
     /* ERR update version is stale */
     $redis->rawCommand("EXSET", "foo", "300", "VER", "10");
     /* Returns : ["OK", " ", VERSION] */
     $redis->rawCommand("EXCAS", "foo", "300", "1");
     ?>
  3. Run the preceding code to connect to the Tair 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 Tair 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: 
    print(r.execute_command('CAS foo bar bzz'))
    print(r.execute_command('CAD foo bzz'))
    print(r.execute_command('EXSET foo 200 VER 1'))
    try:
        r.execute_command('EXSET foo 300 VER 10')
    except:
        print("The attached version is different from the server version, the operation will fail. ")
    print(r.execute_command('EXCAS foo 300 1'))
  3. Run the preceding code to connect to the Tair 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 <iostream>
    #include <string>
    #include <string.h>
    #include <hiredis/hiredis.h>
    using namespace std;
     
    int main(int argc, char **argv) {
        unsigned int j;
        redisContext *c;
        redisReply *reply;
        if (argc < 3) {
                printf("Usage: example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 password\n");
                exit(0);
        }
        const char *hostname = argv[1];
        const int port = atoi(argv[2]);
        const char *password = argv[3];
        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 = (redisReply *)redisCommand(c, "AUTH %s", password);
        printf("AUTH: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* PING server */
        reply = (redisReply *)redisCommand(c,"PING");
        printf("PING: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* The following code provides an example on how to use the TairString data module. */
        reply = (redisReply *)redisCommand(c,"SET foo bar");
        printf("SET: %s\n", reply->str);
        freeReplyObject(reply);
    
        reply = (redisReply *)redisCommand(c,"CAS foo bar bzz");
        printf("CAS: %lld\n", reply->integer);
        freeReplyObject(reply);
    
        reply = (redisReply *)redisCommand(c,"CAD foo bzz");
        printf("CAD: %lld\n", reply->integer);
        freeReplyObject(reply);
    
        /* TairString exstrtype */
        reply = (redisReply *)redisCommand(c,"EXSET foo 200 VER 1");
        printf("EXSET: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* The attached version is different from the server version, the operation will fail */
        reply = (redisReply *)redisCommand(c,"EXSET foo 300 VER 10");
        printf("EXSET: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* Compare the specified version to update the value, and the update is successful
        when the version in the engine is the same as the specified one */
        reply = (redisReply *)redisCommand(c,"EXCAS foo 300 1");
        if (reply->type == REDIS_REPLY_ARRAY) {
            /* ["OK", "", version], The middle value is an empty string, meaningless when successful */
            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 Tair 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 System;
    using StackExchange.Redis;
    
    namespace CSharpTestRedis
    {
        class Program
        {  
            // Specify the endpoint, port number, and password of the Tair instance. 
    		private static ConfigurationOptions connDCS = ConfigurationOptions.Parse("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,password=testaccount:Rp829dlwa");
            //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(connDCS);
                        }
                    }
                }
                return redisConn;
            }
            static void Main(string[] args)
            {
                redisConn = getRedisConn();
                var db = redisConn.GetDatabase();
    
                var ret = db.Execute("set", "foo", "bal");
                Console.WriteLine("set " + ret);
                ret = db.Execute("CAS", "foo", "bal", "bzz");
                Console.WriteLine("CAS " + ret);
                ret = db.Execute("CAD", "foo", "bzz");
                Console.WriteLine("CAD " + ret);
                ret = db.Execute("EXSET", "foo", "200", "VER", "1");
                Console.WriteLine("EXSET " + ret);
                
                try {
                    ret = db.Execute("EXSET", "foo", "300", "VER", "10");
                    Console.WriteLine("EXSET " + ret);
                } catch (Exception ex) {
                    Console.WriteLine("ERR : " + ex.ToString());
                }
                // ["OK", "", version], The middle value is an empty string, meaningless when successful.
                db.Execute("EXCAS", "foo", "300", "1");
                Console.WriteLine("END");
            }
        }
    }
    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 Tair 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');
    await client.get('foo');
    const value = await client.sendCommand(['CAS', 'foo', 'bar', 'bzz']);
    console.log("cas result: %s", value);
    await client.disconnect();
  3. Run the preceding code to connect to the Tair instance.

go-redis

  1. Download and install the go-redis client.

  2. Enter the following code in the go-redis editor 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 Tair instance.
    		Addr:     "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
            // Specify the password of the instance account.
    		Password: "testaccount:Rp829dlwa", // no password set
    		DB:       0,  // use default DB
    	})
    
    	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 -&gt; ", val)
    	
    	// The following code provides an example on how to use the TairString data module:
    	res, err := client.Do("CAS", "foo", "bar", "bzz").Result()
    	fmt.Println("CAS : ", res)
    
    	res, err = client.Do("CAD", "foo", "bzz").Result()
    	fmt.Println("CAD : "res)
    
    	res, err = client.Do("EXSET", "foo", "200", "VER", "1").Result()
    	fmt.Println("EXSET : ", res)
    
    	res, err = client.Do("EXSET", "foo", "300", "VER", "10").Result()
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println("EXSET : ", res)
    
    	res, err = client.Do("EXCAS", "foo", "300", "1").Result()
    	fmt.Println("EXCAS : ", res)
    }
    
    func main() {
    	ExampleClient()
    }
  3. Run the preceding code to connect to the Tair 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