全部產品
Search
文件中心

Tair:使用直連模式串連Tair

更新時間:Jul 06, 2024

若您購買或開通了雲原生記憶體資料庫Tair直連模式叢集,您可以將原生Redis叢集架構無縫遷移到雲原生記憶體資料庫Tair中。雲原生記憶體資料庫Tair的直連地址支援原生Redis Cluster協議,用戶端將直接與Tair伺服器進行串連。在直連模式下,Tair服務的響應速度非常快。

前提條件

  • 開通直連訪問

  • 將用戶端地址加入至Tair白名單

  • 使用JedisPhpRedis等支援Redis Cluster的用戶端。

    說明
    • 使用不支援Redis Cluster的用戶端,可能因用戶端無法重新導向請求到正確的分區而擷取不到需要的資料。

    • 您可以在Redis官網的用戶端列表裡尋找更多支援Redis Cluster的用戶端。

  • Tair用戶端所在的ECS與目標Tair執行個體為同一VPC網路(相同VPC ID)。

背景資訊

開啟直連模式時,Tair會為叢集中所有資料分區的master節點分配一個虛擬IP(VIP)地址。用戶端在首次向直連地址發送請求前會通過DNS伺服器解析直連地址,解析結果會是叢集中一個隨機資料分區的VIP。擷取到VIP後,用戶端即可通過Redis Cluster協議操作Tair叢集中的資料。下圖展示了直連模式下Tair叢集版的服務架構。

圖 1. Tair叢集版直連模式服務架構Redis叢集版直連模式服務架構

注意事項

  • 由於部署架構的不同,相對標準架構來說,叢集架構執行個體與原生Redis命令的支援上有一定的區別(例如不支援SWAPDB命令、Lua存在使用限制等)。更多資訊,請參見叢集架構與讀寫分離架構的命令限制

  • 如果直連模式下執行變更執行個體配置,系統會採用Slot(槽)遷移的方式來完成,此情境下,用戶端可能因訪問到正在遷移的Slot而提示MOVEDTRYAGAIN等錯誤資訊。如需確保請求的成功執行,請為用戶端設計重試機制。更多資訊,請參見Tair用戶端重連指南

  • 直連模式支援使用SELECT命令切換DB,但部分Redis Cluster用戶端(例如StackExchange.Redis)不支援SELECT命令,如果使用該類用戶端則只能使用DB0。

  • 直連地址僅支援通過阿里雲內網訪問,且同時支援專用網路免密訪問帳號密碼認證

redis-cli

使用叢集架構直連地址串連執行個體。

重要

使用直連地址串連時必須添加-c參數,否則會導致串連失敗。

./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379 -c

完成密碼驗證。

AUTH testaccount:Rp829dlwa

關於redis-cli的更多介紹請參見通過redis-cli串連Tair

Jedis

本樣本的Jedis版本為4.3.0,更多資訊請參見Jedis

  • 使用自訂串連池(推薦)

    import redis.clients.jedis.*;
    import java.util.HashSet;
    import java.util.Set;
    
    public class DirectTest {
        private static final int DEFAULT_TIMEOUT = 2000;
        private static final int DEFAULT_REDIRECTIONS = 5;
        private static final ConnectionPoolConfig config = new ConnectionPoolConfig();
    
        public static void main(String args[]) {
            // 最大空閑串連數,由於直連模式為用戶端直接連接某個資料庫分區,需要保證:業務機器數 * MaxTotal < 單個資料庫分區的最大串連數。
            // 其中社區版單個分區的最大串連數為10,000,企業版單個分區的最大串連數為30,000。
            config.setMaxTotal(30);
            // 最大空閑串連數, 根據業務需要設定。
            config.setMaxIdle(20);
            config.setMinIdle(15);
    
            // 開通直連訪問時申請到的直連地址。
            String host = "r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com";
            int port = 6379;
            // 執行個體的密碼。
            String password = "xxxxx";
    
            Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
            jedisClusterNode.add(new HostAndPort(host, port));
            JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS,
                password, "clientName", config);
    
            jc.set("key", "value");
            jc.get("key");
    
            jc.close();     // 當應用退出,需銷毀資源時,調用此方法。此方法會中斷連線、釋放資源。
        }
    }
  • 使用預設串連池

    import redis.clients.jedis.ConnectionPoolConfig;
    import redis.clients.jedis.HostAndPort;
    import redis.clients.jedis.JedisCluster;
    import java.util.HashSet;
    import java.util.Set;
    
    public class DirectTest{
        private static final int DEFAULT_TIMEOUT = 2000;
        private static final int DEFAULT_REDIRECTIONS = 5;
        private static final ConnectionPoolConfig DEFAULT_CONFIG = new ConnectionPoolConfig();
    
        public static void main(String args[]){
    
            // 開通直連訪問時申請到的直連地址。
            String host = "r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com";
            int port = 6379;
            String password = "xxxx";
    
            Set<HostAndPort>  jedisClusterNode = new HashSet<HostAndPort>();
            jedisClusterNode.add(new HostAndPort(host, port));
    
            JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
                DEFAULT_REDIRECTIONS,password, "clientName", DEFAULT_CONFIG);
    
            jc.set("key","value");
            jc.get("key");
    
            jc.close();     // 當應用退出,需銷毀資源時,調用此方法。此方法會中斷連線、釋放資源。
        }
    }

PhpRedis

本樣本的PhpRedis版本為5.3.7,更多資訊請參見PhpRedis

<?php
 // 直連地址和串連連接埠。
 $array = ['r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com:6379'];
 // 串連密碼。
 $pwd = "xxxx";
 
 // 使用密碼串連叢集。
 $obj_cluster = new RedisCluster(NULL, $array, 1.5, 1.5, true, $pwd);
 
 // 輸出串連結果。
 var_dump($obj_cluster);
 
 if ($obj_cluster->set("foo", "bar") == false) {
     die($obj_cluster->getLastError());
 }
 $value = $obj_cluster->get("foo");
 echo $value;
 ?>

redis-py

本樣本的Python版本為3.9、redis-py版本為4.4.1,更多資訊請參見redis-py

# !/usr/bin/env python
# -*- coding: utf-8 -*-
from redis.cluster import RedisCluster
# 分別將host和port的值替換為執行個體的串連地址、連接埠號碼。
host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
port = 6379
# 分別將user和pwd的值替換為執行個體的帳號和密碼。
user = 'testaccount'
pwd = 'Rp829dlwa'
rc = RedisCluster(host=host, port=port, username=user, password=pwd)
# 串連建立後即可執行資料庫操作,下述代碼為您提供SET與GET的使用樣本。
rc.set('foo', 'bar')
print(rc.get('foo'))

Spring Data Redis

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

  1. 添加下述Maven依賴。

    <?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>
  2. 在Spring Data Redis編輯器中輸入下述代碼,然後根據注釋提示修改代碼。

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

    • Spring Data Redis With Jedis

      @Bean
           JedisConnectionFactory redisConnectionFactory() {
               List<String> clusterNodes = Arrays.asList("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379");
               RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(clusterNodes);
               redisClusterConfiguration.setUsername("user");
               redisClusterConfiguration.setPassword("password");
             
       
               JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
               // 最大空閑串連數,由於直連模式為用戶端直接連接某個資料庫分區,需要保證:業務機器數 * MaxTotal < 單個資料庫分區的最大串連數。
               // 其中社區版單個分區的最大串連數為10,000,企業版單個分區的最大串連數為30,000。
               jedisPoolConfig.setMaxTotal(30);
               // 最大空閑串連數, 根據業務需要設定。
               jedisPoolConfig.setMaxIdle(20);
               // 關閉 testOn[Borrow|Return],防止產生額外的 PING
               jedisPoolConfig.setTestOnBorrow(false);
               jedisPoolConfig.setTestOnReturn(false);
       
               return new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig);
           }
    • Spring Data Redis With Lettuce

           /**
           *  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
          public LettuceConnectionFactory redisConnectionFactory() {
              List<String> clusterNodes = Arrays.asList("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379");
              RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(clusterNodes);
              redisClusterConfiguration.setUsername("user");
              redisClusterConfiguration.setPassword("password");
      
              // 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();
      
              ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                  .enablePeriodicRefresh(Duration.ofSeconds(15))
                  .dynamicRefreshSources(false)
                  .enableAllAdaptiveRefreshTriggers()
                  .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15)).build();
      
              LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder().
                  clientOptions(ClusterClientOptions.builder()
                      .socketOptions(socketOptions)
                      .validateClusterNodeMembership(false)
                      .topologyRefreshOptions(topologyRefreshOptions).build()).build();
      
              return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
          }

      ClusterTopologyRefreshOptions.builder參數說明如下:

      參數

      說明

      樣本(推薦值)

      enablePeriodicRefresh(Duration refreshPeriod)

      啟用定期叢集拓撲重新整理周期,建議為15s,若配置的值太小會產生大量的Cluster Nodes調用,影響效能。

      15s

      dynamicRefreshSources()

      是否採用使用Cluster Nodes中擷取的IP用來作為叢集拓撲重新整理的調用節點。串連Tair執行個體時,需要配置為false。由於Tair執行個體通常都是使用VIP(Virtual IP address),如果在遷移可用性區域的情況下,VIP會全部替換,從而無法重新整理路由。因此關閉這個參數,使用阿里雲提供的網域名稱來查詢Cluster nodes,網域名稱服務 (DNS)會自動進行負載平衡,並且指向當前Tair節點。

      false

      enableAllAdaptiveRefreshTriggers()

      開啟叢集拓撲重新整理,包含遇到MOVED等訊息就自動重新整理叢集一次。

      無需配置

      adaptiveRefreshTriggersTimeout(Duration timeout)

      為防止叢集拓撲重新整理頻率過高,此參數只允許在對應時間內產生一次拓撲重新整理。

      15s

      validateClusterNodeMembership()

      是否校正Cluster節點邏輯,阿里雲Tair執行個體無需校正。

      false

.Net

本樣本的.Net版本為6.0,StackExchange.Redis版本為2.6.90。

using StackExchange.Redis;

class RedisConnSingleton {
    // 分別設定執行個體的串連地址、連接埠號碼和使用者名稱、密碼。
    private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,user=testaccount,password=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;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ConnectionMultiplexer cm = RedisConnSingleton.getRedisConn();
        var db = cm.GetDatabase();
        db.StringSet("key", "value");
        String ret = db.StringGet("key");
        Console.WriteLine("get key: " + ret);
    }
}

node-redis

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

import { createCluster } from 'redis';

// 分別設定執行個體的連接埠號碼、串連地址、帳號、密碼,
// 注意,在url中配置使用者和密碼之後,還需要在defaults中設定全域使用者和密碼,
// 用於其餘節點的認證,否則將出現NOAUTH的錯誤。

const cluster = createCluster({
    rootNodes: [{
        url: 'redis://testaccount:Rp829dlwa@r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379'
    }],
    defaults: {
        username: 'testaccount',
        password: 'Rp829dlwa'
    }
});

cluster.on('error', (err) => console.log('Redis Cluster Error', err));

await cluster.connect();

await cluster.set('key', 'value');
const value = await cluster.get('key');
console.log('get key: %s', value);

await cluster.disconnect();

Go-redis

本樣本的Go版本為1.19.7、Go-redis版本為9.5.1。

重要

請使用Go-redis v9.0及以上版本,否則在使用直連模式地址時,可能會產生不相容報錯

package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v9"
)

var ctx = context.Background()

func main() {
	rdb := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:    []string{"r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379"},
		Username: "testaccount",
		Password: "Rp829dlwa",
	})

	err := rdb.Set(ctx, "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := rdb.Get(ctx, "key").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("key", val)
}

Lettuce

推薦使用Lettuce 6.3.0及以上版本,Lettuce 6.3.0以下版本存在缺陷,不建議使用。本樣本的Lettuce版本為6.3.0。

  1. 添加下述Maven依賴。

            <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.65.Final</version>
                <classifier>linux-x86_64</classifier>
            </dependency>
  2. 添加下述代碼,並根據注釋提示修改代碼。

    import io.lettuce.core.RedisURI;
    import io.lettuce.core.SocketOptions;
    import io.lettuce.core.cluster.ClusterClientOptions;
    import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
    import io.lettuce.core.cluster.RedisClusterClient;
    import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
    
    import java.time.Duration;
    
    public class ClusterDemo {
        /**
         *  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;
    
        public static void main(String[] args) throws Exception {
            // 分別將host、port和password的值替換為實際的執行個體資訊。
            String host = "r-bp1ln3c4kopj3l****.redis.rds.aliyuncs.com";
            int port = 6379;
            String password = "Da****3";
    
            RedisURI redisURI = RedisURI.Builder.redis(host)
                    .withPort(port)
                    .withPassword(password)
                    .build();
    
            ClusterTopologyRefreshOptions refreshOptions = ClusterTopologyRefreshOptions.builder()
                    .enablePeriodicRefresh(Duration.ofSeconds(15))
                    .dynamicRefreshSources(false)
                    .enableAllAdaptiveRefreshTriggers()
                    .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15)).build();
    
            // Config TCP KeepAlive
            SocketOptions socketOptions = SocketOptions.builder()
                    .keepAlive(SocketOptions.KeepAliveOptions.builder()
                            .enable()
                            .idle(Duration.ofSeconds(TCP_KEEPALIVE_IDLE))
                            .interval(Duration.ofSeconds(TCP_KEEPALIVE_IDLE/3))
                            .count(3)
                            .build())
                    .tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
                            .enable()
                            .tcpUserTimeout(Duration.ofSeconds(TCP_USER_TIMEOUT))
                            .build())
                    .build();
    
            RedisClusterClient redisClient = RedisClusterClient.create(redisURI);
            redisClient.setOptions(ClusterClientOptions.builder()
                    .socketOptions(socketOptions)
                    .validateClusterNodeMembership(false)
                    .topologyRefreshOptions(refreshOptions).build());
    
            StatefulRedisClusterConnection<String, String> connection = redisClient.connect();
            connection.sync().set("key", "value");
            System.out.println(connection.sync().get("key"));
        }
    }
  3. 執行上述代碼,預期會返回如下結果:

    value

    關於ClusterTopologyRefreshOptions.builder參數,請參見上方Spring Data Redis With Lettuce中的說明。

相關文檔

直連模式適用於簡單的應用情境,Tair代理模式提供更高的可拓展性與高可用性,更多資訊請參見Tair Proxy特性說明

常見問題

請參見Tair常見報錯