日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

使用直連模式連接實例

若您購買或開通了云數據庫 Tair(兼容 Redis)直連模式集群,您可以將原生Redis集群架構無縫遷移到該實例中。云數據庫 Tair(兼容 Redis)的直連地址支持原生Redis Cluster協議,在該模式下,客戶端將直接與數據服務器進行連接,服務的響應速度非???。

前提條件

  • 開通直連訪問

  • 將客戶端地址加入實例白名單。

  • 使用Jedis、PhpRedis等支持Redis Cluster的客戶端。

    說明
    • 使用不支持Redis Cluster的客戶端,可能因客戶端無法重定向請求到正確的分片而獲取不到需要的數據。

    • 您可以在Redis官網的客戶端列表里查找更多支持Redis Cluster的客戶端。

  • 客戶端所在的ECS與實例在同一VPC網絡(相同VPC ID)。

背景信息

開啟直連模式時,云數據庫 Tair(兼容 Redis)會為該集群中所有數據分片的master節點分配一個虛擬IP(VIP)地址??蛻舳嗽谑状蜗蛑边B地址發送請求前會通過DNS服務器解析直連地址,解析結果會是集群中一個隨機數據分片的VIP。獲取到VIP后,客戶端即可通過Redis Cluster協議操作該集群中的數據。下圖展示了直連模式下集群的服務架構。

圖 1. 直連模式集群的服務架構Redis集群版直連模式服務架構

注意事項

  • 由于部署架構的不同,相對標準架構來說,集群架構的實例在原生Redis命令的支持上有一定的區別(例如Lua存在使用限制等)。更多信息,請參見集群架構實例的命令限制。

  • 直連模式下,如果執行變更實例配置,系統會采用Slot(槽)遷移的方式來完成,此場景下,客戶端可能因訪問到正在遷移的Slot而提示MOVEDTRYAGAIN等錯誤信息。如需確保請求的成功執行,請為客戶端設計重試機制。更多信息,請參見Redis客戶端重連指南。

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

  • 直連地址僅支持通過阿里云內網訪問,且同時支持VPC免密賬號密碼認證

redis-cli

使用集群架構直連地址連接實例。

重要

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

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

完成密碼驗證。

AUTH testaccount:Rp829dlwa

關于redis-cli的更多介紹請參見通過redis-cli連接實例

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 < 單個數據庫分片的最大連接數。
            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 < 單個數據庫分片的最大連接數。
               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(以及Redis開源版實例時,需要配置為false。由于實例通常都是使用VIP(Virtual IP address),如果在遷移可用區的情況下,VIP會全部替換,從而無法刷新路由。因此關閉這個參數,使用阿里云提供的域名來查詢Cluster nodes,域名服務會自動進行負載均衡,并且指向當前的實例節點。

      false

      enableAllAdaptiveRefreshTriggers()

      開啟集群拓撲刷新,包含遇到MOVED等消息就自動刷新集群一次。

      無需配置

      adaptiveRefreshTriggersTimeout(Duration timeout)

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

      15s

      validateClusterNodeMembership()

      是否校驗Cluster節點邏輯,阿里云Tair(以及Redis開源版實例無需校驗。

      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 Proxy特性說明。

常見問題

請參見常見報錯