全部產品
Search
文件中心

ApsaraDB for Redis:用戶端程式串連Redis

更新時間:Jun 19, 2024

ApsaraDB for Redis與原生Redis完全相容,支援所有原生Redis支援的用戶端,串連資料庫的方式也基本相同,您可以根據自身應用特點選用任何相容Redis協議的用戶端程式。

前提條件

根據用戶端程式的部署位置,完成下述操作:

用戶端程式部署位置

需完成的操作

ECS執行個體(推薦)

  1. 確保ECS執行個體與Redis執行個體屬於同一專用網路(即執行個體基本資料中的專用網路ID一致)。

    說明
  2. 擷取ECS執行個體的內網IP地址。具體操作,請參見查詢ECS執行個體的IP地址

  3. 將ECS執行個體的內網IP地址添加至Redis執行個體的白名單中。具體操作,請參見設定IP白名單

本地

  1. Redis執行個體預設僅提供內網串連地址,通過公網串連時您需要手動申請公網串連地址。具體操作,請參見申請公網串連地址

  2. 擷取本地裝置公網IP地址的方式可能因你所處的網路環境或操作不同而不同。以下是不同系統通過命令方式擷取本地裝置公網IP地址的參考方法:

    • Linux作業系統:開啟終端,輸入curl ifconfig.me命令後斷行符號。

    • Windows作業系統:開啟命令提示字元,輸入curl ip.me命令後斷行符號。

    • macOS作業系統:開啟終端,輸入curl ifconfig.me命令後斷行符號。

  3. 將本地用戶端的公網IP地址添加至Redis執行個體的白名單中。具體操作,請參見設定IP白名單

注意事項

  • 如果您的Redis執行個體為叢集架構讀寫分離架構,執行個體預設會提供Proxy(代理)節點的串連地址,串連方式與串連標準架構的Redis執行個體相同。

    說明

    叢集架構的執行個體通過直連地址串連時,串連方式與串連開源Redis Cluster相同。

  • 如果執行個體開啟了專用網路免密訪問,同一專用網路下的用戶端程式無需設定密碼即可串連Redis執行個體。

如何擷取串連資訊

在使用用戶端程式串連Redis執行個體時,通常您需要擷取以下資訊並設定在代碼中:

需擷取的資訊

擷取方式

執行個體的串連地址

Redis執行個體支援多種串連地址,推薦使用專用網路串連,可獲得更高的安全性和更低的網路延遲。更多資訊,請參見查看串連地址

連接埠號碼

連接埠號碼預設為6379,您也可以自訂連接埠號碼。具體操作,請參見修改串連地址或連接埠

執行個體的帳號(部分用戶端程式無需設定)

Redis執行個體預設會建立一個以執行個體ID命名的帳號(例如r-bp10noxlhcoim2****),您也可以建立一個新的帳號並賦予許可權。更多資訊,請參見建立與管理帳號

帳號的密碼

根據選取帳號的不同,密碼的填寫格式有一定區別:

  • 預設帳號(以執行個體ID命名的帳號):直接填寫密碼即可。

  • 新建立的帳號:密碼格式為<user>:<password>。例如自訂帳號為testaccount,密碼為Rp829dlwa,密碼需填寫為testaccount:Rp829dlwa

說明
  • 如果通過第三方資料庫管理工具(例如RDM等)串連Redis執行個體,請在密碼框中輸入user:password進行串連。

  • 如果忘記密碼,您可以重設密碼。具體操作,請參見修改或重設密碼

常見用戶端樣本

關於Redis支援的用戶端列表請參見Redis Clients

重要

本文僅列舉常見用戶端程式串連Redis的程式碼範例,協助您快速串連,如需查看通過用戶端程式串連Tair(Redis企業版)的程式碼範例,請參見用戶端程式串連Tair

Jedis

本樣本使用Maven方式進行構建,您也可以手動下載Jedis用戶端。

  1. 開啟編譯器,建立專案。

  2. 添加下述pom檔案。

    本樣本的Jedis版本為4.3.0。

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  3. 在編輯器中輸入下述代碼,然後根據注釋提示修改代碼。

    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();
            // 最大空閑串連數,需自行評估,不超過Redis執行個體的最大串連數。
            config.setMaxIdle(200);
            // 最大串連數,需自行評估,不超過Redis執行個體的最大串連數。
            config.setMaxTotal(300);
            config.setTestOnBorrow(false);
            config.setTestOnReturn(false);
            // 分別將host和password的值替換為執行個體的串連地址、密碼。
            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();
                // 執行相關操作,樣本如下。
                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();    // 當應用退出,需銷毀資源時,調用此方法。此方法會中斷連線、釋放資源。
        }
    }
  4. 運行上述Project,預期會返回如下結果:

    bar
    [bike, car]
    重要

    在使用Jedis的過程中,如果設定了一些不合理的參數或錯誤使用某些功能可能會引起報錯,關於如何排查,請參見常見報錯

PhpRedis

  1. 下載並安裝PhpRedis用戶端。

  2. 在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;
     ?>
  3. 執行上述代碼。

    說明

    常見報錯與解決方案:

redis-py

  1. 下載並安裝redis-py用戶端。

  2. 在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的值替換為執行個體的密碼。
    pwd = 'testaccount:Rp829dlwa'
    r = redis.Redis(host=host, port=port, password=pwd)
    # 串連建立後即可執行資料庫操作,下述代碼為您提供SET與GET的使用樣本。
    r.set('foo', 'bar')
    print(r.get('foo'))
  3. 執行上述代碼。

Spring Data Redis

本樣本使用Maven方式進行構建,您也可以手動下載LettuceJedis用戶端。

  1. 開啟編譯器,建立專案。

  2. 添加下述pom檔案,並下載Lettuce或Jedis。若使用Lettuce,不建議使用Lettuce 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. 在Spring Data Redis編輯器中輸入下述代碼,然後根據注釋提示修改代碼。

    本樣本的Spring Data Redis版本為2.4.2。

    • Spring Data Redis With Jedis

      @Bean
           JedisConnectionFactory redisConnectionFactory() {
               RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", port);
       
               JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
               // 最大串連數, 根據業務需要設定,不能超過執行個體規格規定的最大串連數。
               jedisPoolConfig.setMaxTotal(30);
               // 最大空閑串連數, 根據業務需要設定,不能超過執行個體規格規定的最大串連數。
               jedisPoolConfig.setMaxIdle(20);
               // 關閉 testOn[Borrow|Return],防止產生額外的PING。
               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 {
          /**
           *  TCP_KEEPALIVE開啟,並且配置三個參數分別為:
           *  TCP_KEEPIDLE = 30
           *  TCP_KEEPINTVL = 10
           *  TCP_KEEPCNT = 3
           */
          private static final int TCP_KEEPALIVE_IDLE = 30;
      
          /**
           * TCP_USER_TIMEOUT參數可以避免在故障宕機情境下,Lettuce持續逾時的問題。
           * 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. 執行上述代碼。

C或C++

  1. 下載並安裝C用戶端

  2. 在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 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. 編譯上述代碼。

    gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. 測試回合,完成串連。

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

.NET

  1. 請下載並安裝StackExchange.Redis 2.7.20及以上版本用戶端,更多資訊請參見StackExchange.Redis升級公告

    重要

    不推薦使用ServiceStack.Redis或CSRedis用戶端:

    • 若使用ServiceStack.Redis用戶端時遇到用戶端的相關問題,您需要向該公司購買相關支援人員服務。

    • CSRedis用戶端的原開發人員已停止維護。

  2. 在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");
      //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;
     }
    說明
    • ConfigurationOptions是StackExchange.Redis的核心,它被整個應用程式共用和重用,應該設定為單例,相關參數設定說明,請參見ConfigurationOptions

    • 由於GetDatabase()返回的對象是輕量級的,每次用的時候從ConnectionMultiplexer對象中擷取即可。

       redisConn = getRedisConn();
       var db = redisConn.GetDatabase();
  3. 通過用戶端程式操作常見的資料結構,樣本如下:

    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. 下載並安裝node-redis用戶端。

  2. 在node-redis用戶端中輸入下述代碼,然後根據注釋提示修改代碼。

    本樣本的Node.js版本為19.4.0、node-redis版本為4.5.1。

    import { createClient } from 'redis';
    
    // 分別設定執行個體的連接埠號碼、串連地址、帳號、密碼
    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();
    說明

    若提示SyntaxError: Cannot use import statement outside a module,請將.js檔案的尾碼改為.mjs,並在調用時增加--experimental-modules選項,例如node --experimental-modules redis.mjs

  3. 執行上述代碼。

Go-redis

  1. 下載並安裝Go-Redis用戶端。

  2. 在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()
    }
  3. 執行上述代碼。

Lettuce

本樣本使用Maven方式進行構建,您也可以手動下載Lettuce用戶端。

  1. 開啟編譯器,建立專案。

  2. 添加下述pom檔案,並下載Lettuce 6.3.0,不建議使用Lettuce 6.3.0以下的版本。

    本樣本的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>
  3. 在編輯器中輸入下述代碼,然後根據注釋提示修改代碼。

    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開啟,並且配置三個參數分別為:
         *  TCP_KEEPIDLE = 30
         *  TCP_KEEPINTVL = 10
         *  TCP_KEEPCNT = 3
         */
        private static final int TCP_KEEPALIVE_IDLE = 30;
    
        /**
         * TCP_USER_TIMEOUT參數可以避免在故障宕機情境下,Lettuce持續逾時的問題。
         * 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) {
            // 分別將host、user、password和port的值替換為實際的執行個體資訊。
            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"));
    
            // 當應用退出,需銷毀資源時,調用此方法。此方法會中斷連線、釋放資源。
            connection.close();
            client.shutdown();
        }
    }
  4. 執行上述代碼,預期會返回如下結果:

    OK
    bar