全部產品
Search
文件中心

Tair (Redis® OSS-Compatible):串連指南

更新時間:Sep 24, 2025

本文將指導您串連Tair(以及Redis開源版執行個體。您需要打通網路和設定白名單,串連執行個體。

打通網路和設定白名單

在串連執行個體前,您需要打通用戶端與執行個體的網路連接並設定IP白名單,具體內容請參見串連準備

串連Tair(以及Redis開源版

請根據以下表格擷取串連執行個體所需參數。

參數

說明

擷取方式

hostname

串連地址

  1. 訪問執行個體列表,在上方選擇地區,然後單擊目標執行個體ID。

  2. 執行個體資訊頁面下方串連資訊地區,可查看到各連線類型的地址和連接埠號碼。

    說明
    • 如需使用公網串連執行個體,請先申請該執行個體的公網串連地址

    • 直連模式的叢集架構雲原生版執行個體不支援申請公網,更多資訊請參見查看串連地址

port

連接埠號碼

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

password

密碼

根據使用帳號類型,填寫帳號、密碼:

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

  • 普通帳號:密碼格式為user:password。例如自訂帳號為testaccount,密碼為Rp829dlwa,密碼需填寫為testaccount:Rp829dlwa

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

redis-cli串連

如果您的裝置未安裝redis-cli,請參考下述安裝說明進行安裝。

redis-cli安裝說明

在ECS執行個體或本地裝置上,安裝Redis會同步安裝redis-cli。通過redis-cli串連時,redis-cli的版本無需與雲資料庫 Tair(相容 Redis)執行個體版本相同。

  1. 登入待安裝redis-cli的裝置,例如ECS執行個體或本地裝置。

  2. 下載、安裝redis-cli。

    Linux系統

    執行下述命令,安裝gcc依賴環境。

    sudo yum -y install gcc

    執行下述命令下載Redis源碼檔案。

    wget https://download.redis.io/releases/redis-7.2.0.tar.gz
    說明

    本文以redis-7.2.0版本為例示範操作流程,您也可以安裝其他版本。具體操作,請參見Redis官網

    執行下述命令解壓Redis源碼檔案。

    tar xzf redis-7.2.0.tar.gz

    執行下述命令進入解壓後的目錄並編譯安裝Redis源碼檔案:

    cd redis-7.2.0&&make
    說明

    編譯安裝需要一段時間(通常為2分鐘~3分鐘)。

    macOS系統

    macOS系統可通過Homebrew包管理器安裝Redis用戶端。下面是詳細的步驟:

    安裝Homebrew(如果尚未安裝)

    1. 開啟終端(Terminal)。

    2. 複製並粘貼以下命令到終端,然後按斷行符號鍵。這個命令會下載並運行Homebrew的安裝指令碼。

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    1. 按照工具提示操作,可能需要輸入密碼。

    使用Homebrew安裝Redis

    在終端中,輸入以下命令來安裝Redis工具集(含redis-cli):

    brew install redis

    這個命令會下載Redis的最新穩定版本並安裝到你的系統中。安裝成功後可在終端輸入命令which redis-cli擷取redis-cli的位置。

    Windows系統

    目前僅支援64位的Windows系統。

    1. 下載Redis-x64-3.2.100.zip檔案。

      說明

      本文以redis-3.2版本為例示範操作流程,您也可以安裝其他版本。更多資訊,請參見MicrosoftArchive-Redis

    2. Redis-x64-3.2.100.zip解壓至待安裝的目錄。

串連執行個體:

  1. 進入redis-cli安裝目錄下。

    Linux系統

    進入..\redis-7.2.0\src所屬的目錄,例如cd /home/redis-7.2.0/src

    macOS系統

    進入../redis-cli所屬的目錄,例如cd /opt/homebrew/bin

    Windows系統

    開啟命令列視窗,進入redis-cli所屬的目錄。

  2. 執行下述命令通過redis-cli串連執行個體:

    ./redis-cli -h <hostname> -p <port> [-c]
    說明

    在Windows中使用PowerShell啟動redis-cli的命令為.\redis-cli -h hostname -p port [-c]

    串連樣本:

    • 預設地址(適用於通過預設地址串連的情境,例如標準架構執行個體的串連地址或叢集架構執行個體的Proxy 位址):

      ./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379
    • 叢集架構直連地址(適用於叢集架構通過直連地址串連的情境):

      ./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379 -c
  3. 執行下述命令完成密碼驗證:

    AUTH <password>

    樣本:

    AUTH testaccount:Rp829dlwa

代碼串連

Spring Data Redis

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

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

  2. 添加下述pom檔案,並下載Lettuce或Jedis。

    重要

    若使用Lettuce,為避免Lettuce用戶端黑洞問題帶來的影響,建議使用6.3.0.RELEASE及以上版本,並設定TCP_USER_TIMEOUT參數。

    <?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

      @Configuration
      public class RedisConfig {
          
          @Bean
          JedisConnectionFactory redisConnectionFactory() {
              //本案例僅用於測試連接,生產環境建議將串連資訊填寫到設定檔中,通過@Value註解讀取
              //串連地址(hostName)和連接埠(port)在執行個體詳情頁下方串連資訊地區擷取,請根據用戶端網路環境選擇專用網路或公網串連
              RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("r-8vbwds91ie1rdl****.redis.zhangbei.rds.aliyuncs.com", 6379);
              //password填寫格式為 帳號:密碼,例如:帳號testaccount,密碼Rp829dlwa,password填寫testaccount:Rp829dlwa
              //忘記帳號密碼請在執行個體詳情頁左側菜單列表點擊帳號管理重設密碼或建立帳號
              config.setPassword(RedisPassword.of("帳號:密碼"));
              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);
          }
          @Bean
          public RedisTemplate<String, Object> redisTemplate() {
              RedisTemplate<String, Object> template = new RedisTemplate<>();
              template.setConnectionFactory(redisConnectionFactory());
              template.setKeySerializer(new StringRedisSerializer());
              template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
              return template;
          }
      }
    • Spring Data Redis With Lettuce (包含設定TCP_USER_TIMEOUT參數)

      @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;
          }
      }

Jedis

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

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

  2. pom.xml檔案中添加下述代碼。

    本樣本的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);
            // 分別將hostname和password的值替換為執行個體的串連地址、密碼。
            String hostname = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com";
            // 預設帳號password可直接填寫密碼;建立帳號password填寫格式為 帳號:密碼,例如建立帳號testaccount,密碼Rp829dlwa,password填寫testaccount:Rp829dlwa。
            String password = "r-bp1s1bt2tlq3p1****:Database123";
            JedisPool pool = new JedisPool(config, hostname, 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]

redis-py

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

  2. 在Python編輯器中輸入下述代碼,然後根據注釋提示修改代碼。

    本樣本的Python版本為3.9、redis-py版本為4.4.1。

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    import redis
    # 分別將hostname和port的值替換為執行個體的串連地址、連接埠號碼。
    hostname = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    # 將pwd的值替換為執行個體的密碼。
    # 預設帳號password可直接填寫密碼;建立帳號password填寫格式 帳號:密碼,例如建立帳號testaccount,密碼Rp829dlwa,password填寫testaccount:Rp829dlwa。
    password = 'testaccount:Rp829dlwa'
    r = redis.Redis(host=hostname, port=port, password=password)
    # 串連建立後即可執行資料庫操作,下述代碼為您提供SET與GET的使用樣本。
    r.set('foo', 'bar')
    print(r.get('foo'))
  3. 運行上述Project,預期會返回如下結果:

    b'bar'

PhpRedis

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

  2. 在PHP編輯器中輸入下述代碼,然後根據注釋提示修改代碼。

    本樣本的PHP版本為8.2.1、PhpRedis版本為5.3.7。

    <?php
     /* 分別將hostname和port的值替換為執行個體的串連地址、連接埠號碼。 */
     $hostname = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
     $port = 6379;
     /* 分別將user和password的值替換為執行個體的帳號和密碼 */
     $user = "testaccount";
     $password = "Rp829dlwa";
     $redis = new Redis();
     if ($redis->connect($hostname, $port) == false) {
             die($redis->getLastError());
       }
     if ($redis->auth([$user, $password]) == false) {
             die($redis->getLastError());
      }
      /* 完成認證後可執行資料庫操作,下述代碼為您提供SET與GET的使用樣本。 */
     if ($redis->set("foo", "bar") == false) {
             die($redis->getLastError());
     }
     $value = $redis->get("foo");
     echo $value;
     ?>
  3. 執行上述代碼。

    說明

    常見報錯與解決方案:

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();

node-redis

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

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

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

    import { createClient } from 'redis';
    
    // 分別設定執行個體的連接埠號碼、串連地址、帳號、密碼
    const hostname = '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]@[hostname][:port]/[db-number]
      url: `redis://${username}:${password}@${hostname}:${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

  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()
    }

Lettuce

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

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

  2. 添加下述pom.xml檔案,並下載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 RedisURI
            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

DMS串連

  1. 訪問執行個體列表,在上方選擇地區,然後單擊目標執行個體ID。

  2. 在頁面右上方,單擊登入資料庫

  3. 在跳轉到的DMS控制台,設定登入方式。

    訪問方式

    說明

    帳號+密碼登入

    (推薦)

    分別填寫資料庫帳號和對應的密碼,關於如何建立資料庫帳號,請參見建立與管理帳號

    說明

    通常執行個體包含一個以執行個體ID命名的資料庫帳號(例如r-bp10noxlhcoim2****),您也可以通過該帳號來登入(密碼在您建立執行個體時已設定)。

    免密登入

    若執行個體已開啟免密訪問,選擇該方式無需填寫密碼即可直接登入。具體操作,請參見開啟專用網路免密訪問

    密碼登入

    使用建立執行個體時設定的密碼登入(即以執行個體ID命名的資料庫帳號對應的密碼)。

    說明

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

    其他參數可保持預設。

  4. 單擊登入

    如您沒有將DMS伺服器的IP地址添加至執行個體的白名單中,系統將彈出對話方塊提示,您需要單擊設定白名單,系統會為執行個體建立一個名為ali_dms_group的白名單分組,並將DMS伺服器的IP地址加入該分組中。

  5. 完成登入後,即可在SQLConsole頁簽對應的文字框中輸入並執行命令,例如執行DBSIZE命令查詢當前庫有多少個鍵(Key)。

    關於Tair(以及Redis開源版支援的命令,請參見命令概覽

其他串連方式

  • 使用直連模式串連執行個體:叢集架構執行個體可申請直連地址,通過該地址可直接存取後端的資料分區(類似串連原生Redis叢集)。相比 代理模式 ,直連模式節約了通過代理處理請求的時間,可以在一定程度上提高執行個體的響應速度。

  • 啟用TLS(SSL)加密串連執行個體:啟用TLS加密功能提高資料鏈路的安全性,保障資料的完整性。

  • 使用Sentinel相容模式串連執行個體:執行個體提供Sentinel(哨兵)相容模式,開啟後用戶端可以像串連原生Redis Sentinel一樣串連執行個體。

串連問題排查

Tair串連問題排查流程