This topic describes how to connect to Tair (and Redis Open-Source Edition) instances. You need to establish network connectivity and configure whitelists to connect to instances.
Establish network connectivity and configure whitelists
Before you connect to an instance, you need to establish network connectivity between your client and the instance, and configure IP address whitelists. For more information, see Prepare for connections.
Connect to Tair (and Redis Open-Source Edition)
Use the following table to obtain the parameters required to connect to an instance.
Parameter | Description | How to obtain |
hostname | Connection address |
|
port | Port number | The default port number is 6379. You can also use a custom port number. For more information, see Modify connection addresses or port numbers. |
password | Password | Enter the account and password based on the account type:
If you forget the password or have not set a password, you can reset the password. For more information, see Modify or reset the password. |
Connect using redis-cli
If you do not have redis-cli installed on your device, refer to the following instructions.
Connect to the instance:
Go to the directory in which redis-cli is installed.
Windows operating system
Open the CLI and go to the directory in which redis-cli is installed.
macOS
Go to the directory in which redis-cli is installed, such as
cd /opt/homebrew/bin
.Linux servers
Go to the directory in which redis-7.0.0\src is installed, such as
cd /home/redis-7.0.0/src
.Run the following command to connect to the instance using redis-cli:
./redis-cli -h <hostname> -p <port> [-c]
NoteIn Windows, the command to start redis-cli in PowerShell is
.\redis-cli -h hostname -p port [-c]
.Sample command:
The following sample command is suitable for scenarios in which ApsaraDB for Redis instances are connected by using default endpoints, such as endpoints of standard instances and proxy endpoints of cluster instances:
./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379
The following sample command is suitable for scenarios in which ApsaraDB for Redis cluster instances are connected by using private endpoints:
./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379 -c
Run the following command to complete authentication:
AUTH <password>
Example:
AUTH testaccount:Rp829dlwa
Connect using code
Spring Data Redis
This example uses Maven for building. You can also manually download the Lettuce or Jedis client.
Open the compiler and create a project.
Add the following
pom
file and download Lettuce or Jedis.ImportantIf you use Lettuce, we recommend that you use 6.3.0.RELEASE or later and configure the TCP_USER_TIMEOUT parameter. This prevents blackhole filtering on the Lettuce client.
<?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>
Enter the following code in a Spring Data Redis editor and modify the code based on the comments.
In this example, Spring Data Redis 2.4.2 is used.
Spring Data Redis With Jedis
@Configuration public class RedisConfig { @Bean JedisConnectionFactory redisConnectionFactory() { //This example is only for testing connections. In production environments, we recommend that you store connection information in configuration files and read it using the @Value annotation. //You can obtain the connection address (hostName) and port number (port) from the Connection Information section at the bottom of the Instance Details page. Select a private or public connection based on your client network environment. RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("r-8vbwds91ie1rdl****.redis.zhangbei.rds.aliyuncs.com", 6379); //Enter the password in the format of username:password. For example, if the username is testaccount and the password is Rp829dlwa, enter testaccount:Rp829dlwa as the password. //If you forget your username or password, click Account Management in the left-side navigation pane of the Instance Details page to reset the password or create an account. config.setPassword(RedisPassword.of("username:password")); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // Specify the maximum number of connections based on your business needs. This value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance. jedisPoolConfig.setMaxTotal(30); // Specify the maximum number of idle connections based on your business needs. This value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance. jedisPoolConfig.setMaxIdle(20); // Disable testOn[Borrow|Return] to prevent additional PING commands from being generated. 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 (including configuration of the TCP_USER_TIMEOUT parameter)
@Configuration public class BeanConfig { /** * Enable TCP keepalive and configure the following three parameters: * TCP_KEEPIDLE = 30 * TCP_KEEPINTVL = 10 * TCP_KEEPCNT = 3 */ private static final int TCP_KEEPALIVE_IDLE = 30; /** * The TCP_USER_TIMEOUT parameter can avoid situations where Lettuce remains stuck in a continuous timeout loop during a failure or crash event. * 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
This example uses Maven for building. You can also manually download the Jedis client.
Open the compiler and create a project.
Add the following code to the
pom.xml
file.In this example, Jedis 4.3.0 is used.
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency>
Enter the following code in the editor and modify the code based on the comments:
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(); // Maximum number of idle connections allowed. You can set this parameter based on your needs. Make sure that the specified value does not exceed the maximum number of connections that the ApsaraDB for Redis instance supports. config.setMaxIdle(200); // Maximum number of connections allowed. You can set this parameter based on your needs. Make sure that the specified value does not exceed the maximum number of connections that the ApsaraDB for Redis instance supports. config.setMaxTotal(300); config.setTestOnBorrow(false); config.setTestOnReturn(false); // Specify the endpoint and password of the instance. String hostname = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com"; // If you use the default account, directly enter the password. If you use a custom account, enter the password in the <Username>:<Password> format. For example, if the username of the custom account is testaccount and the password is Rp829dlwa, enter testaccount:Rp829dlwa as the password. String password = "r-bp1s1bt2tlq3p1****:Database123"; JedisPool pool = new JedisPool(config, hostname, 6379, 3000, password); Jedis jedis = null; try { jedis = pool.getResource(); // Refer to the following example to perform related operations: 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) { // Handle timeout errors or other exceptions. e.printStackTrace(); } finally { if (jedis != null) { jedis.close(); } } pool.destroy(); // If your application exits and you want to destroy the resources, call this method. This way, the connection is closed, and the resources are released. } }
Run the preceding code. The following output is expected on successful completion:
bar [bike, car]
redis-py
Download and install the redis-py client.
Enter the following code in the Python editor and modify the code based on the comments.
In this example, Python 3.9 and redis-py 4.4.1 are used.
#!/usr/bin/env python #-*- coding: utf-8 -*- import redis # Specify the endpoint and port number of the instance. hostname = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com' port = 6379 # Replace the value of the pwd parameter with the password of the instance account. # If you use the default account, directly enter the password. If you use a custom account, enter the password in the <Username>:<Password> format. For example, if the username of the custom account is testaccount and the password is Rp829dlwa, enter testaccount:Rp829dlwa as the password. password = 'testaccount:Rp829dlwa' r = redis.Redis(host=hostname, port=port, password=password) # You can perform operations on the instance after the connection is established. For example, you can run the following code to call the SET and GET methods. r.set('foo', 'bar') print(r.get('foo'))
Run the preceding code. The following output is expected on successful completion:
b'bar'
PhpRedis
Download and install the PhpRedis client.
Enter the following code in a PHP editor and modify the code based on the comments.
In this example, PHP 8.2.1 and PhpRedis 5.3.7 are used.
<?php /* Specify the endpoint and port number of the ApsaraDB for Redis instance. */ $hostname = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com"; $port = 6379; /* Specify the username and password of the instance account */ $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()); } /* You can perform operations on the instance after the connection is established. For example, you can run the following code to call the set and get methods. */ if ($redis->set("foo", "bar") == false) { die($redis->getLastError()); } $value = $redis->get("foo"); echo $value; ?>
Run the preceding code.
NoteCommon errors and solutions:
Cannot assign requested address
: For information about the cause of and solution to the error, see What do I do if the "Cannot assign requested address" error is returned when I access ApsaraDB for Redis over short-lived connections?redis protocol error, got ' ' as reply type byte
: Update the version of your PhpRedis client. For more information, visit GitHub.
C or C++
Download and install the C client.
Enter the following code in a C or C++ editor and modify the code based on the comments.
In this example, hiredis 1.1.0 is used.
#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; }
Compile the code.
gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
Perform a test run and connect to the ApsaraDB for Redis instance.
./example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 r-bp10noxlhcoim2**** password
.NET
Download and install StackExchange.Redis 2.7.20 or later. For more information, see StackExchange.Redis upgrade announcement.
ImportantWe recommend that you do not use the ServiceStack Redis or CSRedis client.
If you use ServiceStack Redis and run into issues related to the client, you must purchase technical support from ServiceStack.
The support for the CSRedis client has been ended.
Enter the following code in a StackExchange.Redis editor and modify the code based on the comments.
In this example, StackExchange.Redis 2.7.20 is used.
using StackExchange.Redis; // Specify the endpoint, port number, and password of the instance. 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; }
NoteConfigurationOptions is the core of StackExchange.Redis. It is shared and reused by the entire application and should be set as a singleton. For more information about parameter settings, see ConfigurationOptions.
The object returned by
GetDatabase()
is lightweight. You can obtain it from the ConnectionMultiplexer object each time you use it.redisConn = getRedisConn(); var db = redisConn.GetDatabase();
node-redis
Download and install the node-redis client.
Enter the following code in the node-redis client and modify the code based on the comments.
In this example, Node.js 19.4.0 and node-redis 4.5.1 are used.
import { createClient } from 'redis'; // Specify the port number, endpoint, username, and password of the instance const hostname = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'; const port = 6379; const username = 'testaccount'; // If the password contains special characters (!@#$%^&*()+-=_), we recommend that you encode the password by using 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();
NoteIf the
SyntaxError: Cannot use import statement outside a module
error is reported, change the extension of the.js
file to.mjs
and add the--experimental-modules
option when you call the file. For example,node --experimental-modules redis.mjs
.
Go-redis
Download and install the Go-Redis client.
Enter the following code in the go-redis client and modify the code based on the comments:
In this example, Go 1.18.5 and go-redis 8.11.5 are used.
package main import ( "github.com/go-redis/redis" "fmt" ) func ExampleClient() { client := redis.NewClient(&redis.Options{ // Specify the endpoint and port number of the instance Addr: "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379", // Specify the password of the instance account Password: "testaccount:Rp829dlwa", DB: 0, // use default DB }) // The following code provides an example on how to call the set and get methods. 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
Connect using DMS
Log on to the console and go to the Instances page. In the top navigation bar, select the region in which the instance that you want to manage resides. Then, find the instance and click the instance ID.
In the upper-right corner of the page, click Log into Database.
In the DMS console, set the logon method.
Access method
Description
Username & Password
(Recommended)
Enter the database account and the corresponding password. For information about how to create a database account, see Create and manage accounts.
NoteBy default, an instance comes with a database account named after the instance ID, such as r-bp10noxlhcoim2****. You can use this account for logon. The account password was specified when you created the instance.
No Password
If password-free access is enabled for the instance, you can log on to the instance without using a password. For more information, see Enable password-free access for a VPC.
Password
Use the password that you specified when you created the instance to log on to the instance. The password is created for the database account that is named after the instance ID.
NoteIf you forget your password, you can reset it. For more information, see Modify or reset the password.
You can keep other parameters as default.
Click Log On.
If you have not added the IP address of the DMS server to the whitelist of the instance, the system displays a dialog box. You need to click Set Whitelist. The system creates a whitelist group named ali_dms_group for the instance and adds the IP address of the DMS server to this group.
After you log on, you can enter and execute commands in the text box on the SQLConsole tab. For example, you can execute the DBSIZE command to query the number of keys in the current database.
For commands supported by Tair (and Redis Open-Source Edition), see Command overview.
Other connection methods
Connect to an instance in direct connection mode: You can request a direct connection address for a cluster architecture instance to directly access the backend data shards (similar to connecting to a native Redis cluster). Compared with proxy mode , the direct connection mode reduces the response time because requests do not need to pass through proxy nodes, which improves the response speed of the instance to some extent.
Enable TLS (SSL) encrypted connections to an instance: Enable the TLS encryption feature to improve the security of the data link and ensure data integrity.
Connect to an instance in Sentinel-compatible mode: The instance provides Sentinel compatibility mode. After this mode is enabled, clients can connect to the instance in the same way as they connect to a native Redis Sentinel.