连接指南

更新时间: 2025-05-16 09:57:29

本文将指导您连接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.0.0.tar.gz
    说明

    本文以redis-7.0.0版本为例演示操作流程,您也可以安装其他版本。具体操作,请参见Redis官网

    执行下述命令解压Redis源码文件。

    tar xzf redis-7.0.0.tar.gz

    执行下述命令进入解压后的目录并编译安装Redis源码文件:

    cd redis-7.0.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安装目录下。

    Windows系统

    打开命令行窗口,进入redis-cli所属的目录。

    macOS系统

    进入../redis-cli所属的目录,例如cd /opt/homebrew/bin

    Linux系统

    进入..\redis-7.0.0\src所属的目录,例如cd /home/redis-7.0.0/src

  2. 执行下述命令通过redis-cli连接实例:

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

    在Windows中使用PowerShell启动redis-cli的命令为.\redis-cli -h hostname -p port [-c]

    连接示例:

    • 默认地址(适用于通过默认地址连接的场景,例如标准架构实例的连接地址或集群架构实例的代理地址):

      ./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连接问题排查流程

上一篇: 登录控制台 下一篇: 连接准备
阿里云首页 云数据库 Tair(兼容 Redis) 相关技术圈