Once you get a private endpoint, you can bypass the proxy nodes and use the private endpoint to connect to aThreecluster instance. This reduces response time.Three🇧🇷 This topic describes the precautions and method of using a private endpoint to connect to a Tair cluster instance. This theme uses Jedis and PhpRedis clients.
requirements
- Direct connect mode is enabled for the cluster instance. For more information, seeEnable direct connection mode.
- The client's IP address is added to a whitelist on the Tair cluster instance. For more information, seeConfigure whitelists.
- A Redis Cluster compatible client is used, such asjediyPhpRedisGenericName.
Use
- If you use a client that doesn't support Redis Cluster, you might not be able to retrieve data because the client can't redirect your request to the correct shard.
- Jedis uses the JedisCluster class to support Redis clusters. For more information, seeClasse JediCluster.
- For a list of supported clients for Redis clusters, seeCustomersPage on the official Redis site.
(Video) OpenStack Tutorial – Operate Your Own Private Cloud (Full Course) - The Elastic Compute Service (ECS) instance on whichThreeThe client is deployed and the Tair cluster instance is in the same virtual private cloud (VPC).
context information
if you activate itdirect connect mode,Threeassigns a virtual IP (VIP) address to the head node of each data shard in the cluster instance. Before a client sends the first request for a private endpoint, the client uses a Domain Name Server (DNS) to resolve the private endpoint. The resolution result is the VIP address of a random data chunk in the cluster instance. The customer can manage the data through this VIP addressThreeCluster instance via the Redis cluster protocol. The following figure shows the service architecture of aThreeCluster instance in direct connect mode.
Precautions
- Tair instances of different architectures provide different support for native Redis commands. For example, the cluster architecture does not support theSWAPDBcommand and has limitations for Lua scripts. For more information, seeLimitations on commands supported by cluster instances.
- When you change an instance's settings while it's in direct connect mode, a slot migration is performed during the process. In this case, the client may receive error messages such as
TOUCHED
yTRY AGAIN
when the client accesses the slots to migrate. For more information about changing an instance's settings, seeChange an instance's settings🇧🇷 To ensure successful execution of the request, configure a retry mechanism for the client. For more information, seeRetry Mechanisms for Redis Clients. - In direct connection mode, you can use theSELECTCommand to alter the database. However, some Redis cluster clients do not support theSELECTcommand, eg. B. StackExchange.redis. If you use StackExchange.redis, you can only use database 0.
- Private endpoints can only be used to access Tair cluster instances through Alibaba Cloud's internal network. If you use a cluster instance's private endpoint to access the instance,passwordless accessyAccount and password authenticationthey are compatible.
Sample code for connecting Jedis to a cluster instance
import redis.clients.jedis.HostAndPort; importar redis.clients.jedis.JedisCluster; importar redis.clients.jedis.JedisPoolConfig; importar java.util.HashSet; importar java.util.Set; public class DirectTest { private static final int DEFAULT_TIMEOUT = 2000; private static final int DEFAULT_REDIRECTIONS = 5; JedisPoolConfig final static private DEFAULT_CONFIG = new JedisPoolConfig(); public static void main(String args[]){ // Especifique o endpoint privado que você aplicou à instância do cluster. host string = "r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com"; porta int = 6379; string de senha = "xxxx"; Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort(host, porta)); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, senha, "clientName", DEFAULT_CONFIG); jc.set("chave","valor"); jc.get("chave"); jc.close(); } }
import redis.jedis.clients.*; import java.util.HashSet; import java.util.Set; public class main { private static final int DEFAULT_TIMEOUT = 2000; private static final int DEFAULT_REDIRECTIONS = 5; JedisPoolConfig final static private DEFAULT_CONFIG = new JedisPoolConfig(); public static void main(String args[]){ JedisPoolConfig config = new JedisPoolConfig(); // Specify the maximum number of idle connections. In direct connection mode, the client connects directly to a shard of a cluster instance. Therefore, the following requirement must be met: number of clients × MaxTotal value < maximum number of connections for a single shard. // Set the maximum number of connections for a shard of an ApsaraDB for Redis Community Edition instance to 10,000 and the maximum number of connections for a shard of a Tair instance to 30,000. config.setMaxTotal(30); // Specify the maximum number of idle connections based on your business needs. config.setMaxIdle(20); config.setTestOnBorrow(false); config.setTestOnReturn(false); // Specify the private endpoint that you applied to the cluster instance. host string = "r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com"; port int = 6379; // Specify the password for the instance. password string = "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); 🇧🇷
UseFor more information on using Jedis, seeGitHub.
Sample code to connect PhpRedis to a cluster instance
<?php // Specify the private endpoint and port number to connect to the cluster instance. $array = ['r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com:6379']; // Provide the password for the connection. $password = "xxxx"; // Use the password to connect to the cluster instance. $obj_cluster = new RedisCluster(NULL, $array, 1.5, 1.5, true, $pwd); // Show the result of the connection. var_dump($obj_cluster); if ($obj_cluster->set("foo", "bar") == false) { die($obj_cluster->getLastError()); } $value = $obj_cluster->get("foo"); echo $value; 🇧🇷
UseFor more information on how to use PhpRedis, seeGitHub.
Sample Code for Connecting Spring Data Redis to a Cluster Instance
@Bean JedisConnectionFactory redisConnectionFactory() { List<String> clusterNodes = Arrays.asList("host1:port1", "host2:port2", "host3:port3"); RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(clusterNodes); redisClusterConfiguration.setPassword("xxx"); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // Specify the maximum number of idle connections. In direct connection mode, the client connects directly to a shard of a cluster instance. Therefore, the following requirement must be met: number of clients × MaxTotal value < maximum number of connections for a single shard. // Set the maximum number of connections for a shard of an ApsaraDB for Redis Community Edition instance to 10,000 and the maximum number of connections for a shard of a Tair instance to 30,000. jedisPoolConfig.setMaxTotal(30); // Specify the maximum number of idle connections based on your business needs. jedisPoolConfig.setMaxIdle(20); // Disable testOn[Borrow|Return] to prevent additional pings from being generated. jedisPoolConfig.setTestOnBorrow(false); jedisPoolConfig.setTestOnReturn(false); return new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig); 🇧🇷
@Bean public LettuceConnectionFactory redisConnectionFactory() { List<String> clusterNodes = Arrays.asList("host1:port1", "host2:port2", "host3:port3"); RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(clusterNodes); redisClusterConfiguration.setPassword("xxx"); ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh(Duration.ofSeconds(15)) // Specify the interval at which the topology of the cluster instance is refreshed. We recommend setting the interval to 15 seconds. If you set it to a smaller value, too many calls will be sent to the cluster instance nodes. This degrades the performance of the clustered instance. .dynamicRefreshSources(false) // Specify whether to use the IP addresses of the nodes obtained from the topology as the nodes to be called to update the cluster instance topology. When connecting to an ApsaraDB for Redis instance, you must set the parameter to false. .enableAllAdaptiveRefreshTriggers() // Enables all triggers to adaptively update the topology. After enabling adaptive updating, the topology of the cluster instance is automatically updated whenever a runtime event, such as a MOVED redirect, occurs on the cluster instance. .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15)).build(); // Specify the period during which the cluster instance topology can only be updated once. This prevents the topology from being updated frequently. LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder(). clientOptions(ClusterClientOptions.builder() .validateClusterNodeMembership(false) .topologyRefreshOptions(topologyRefreshOptions).build()).build(); returns new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration); 🇧🇷
UseFor more information on using Spring Data Redis, seeFeder.
Sample code for connecting salad to a cluster instance
The Lettuce client supports synchronous and asynchronous communication using the Redis APIs. The Lettuce client does not automatically reconnect to an instance after multiple requests time out. If Tair fails and causes the proxy nodes or data nodes to fail, the connection may time out. This may result in the inability to reconnect to Tair. To avoid this issue, we recommend using other clients.
public class ClusterDemo { public static void main(String[] args) throws Exception { String host = "r-bp1xxxxxxxxxxxx.redis.rds.aliyuncs.com"; port int = 30001; password string = "xxxx"; RedisURI redisURI = RedisURI.Builder.redis(host).withPort(port).withPassword(password).build(); ClusterTopologyRefreshOptions refreshOptions = ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh(Duration.ofSeconds(15)) // Specify the interval at which the topology of the cluster instance is refreshed. We recommend setting the interval to 15 seconds. If you set it to a smaller value, too many calls will be sent to the cluster instance nodes. This degrades the performance of the clustered instance. .dynamicRefreshSources(false) // Specify whether to use the IP addresses of the nodes obtained from the topology as the nodes to be called to update the cluster instance topology. When connecting to a Tair instance, you must set the parameter to false. .enableAllAdaptiveRefreshTriggers() // Enables all triggers to adaptively update the topology. After enabling adaptive updating, the topology of the cluster instance is automatically updated whenever a runtime event, such as a MOVED redirect, occurs on the cluster instance. .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15)).build(); // Specify the period during which the cluster instance topology can only be updated once. This prevents the topology from being updated frequently. RedisClusterClient redisClient = RedisClusterClient.create(redisURI); redisClient.setOptions(ClusterClientOptions.builder() .socketOptions(SocketOptions.builder() .keepAlive(true) // Set the keepalive parameter to true .build()) .validateClusterNodeMembership(false) .topologyRefreshOptions(refreshOptions).build() ) ; StatefulRedisClusterConnection<String, String> connection = redisClient.connect(); connection.sync().set("key", "value"); 🇧🇷
UseFor more information on using lettuce, seeGitHub.
frequently asked questions
- Q: What should I do if the
Connection to xxx not allowed. This partition is not known in the cluster view.
Does an error occur when I use Lettuce to connect to a Tair instance?A: Provide refreshOptions parameter. For more information, seeSample code for connecting salad to a cluster instance.