客户最佳实践(Valkey 和 RedisOSS) - 亚马逊 ElastiCache

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

客户最佳实践(Valkey 和 RedisOSS)

学习常见场景的最佳实践,并遵循一些最受欢迎的开源 Valkey 和 Redis OSS 客户端库(redis-py 和 Lettuce)的代码示例PHPRedis,以及与常用的开源 Memcached 客户端库进行 ElastiCache 资源交互的最佳实践。

为双堆栈集群(Valkey 和 RedisOSS)配置首选协议

对于启用了集群模式的 Valkey 或 Redis OSS 集群,您可以使用 IP 发现参数控制客户端用于连接到集群中节点的协议。IP 发现参数可以设置为IPv4或IPv6。

对于 Valkey 或 Redis OSS 集群,IP 发现参数设置集群插槽 ()、集群分片 () 和集群节点 () 输出中使用的 IP 协议。客户端使用这些命令来发现集群拓扑。客户端使用这些命令连接到群集中的其他节点。IPs

更改 IP 发现不会导致连接的客户端出现任何停机。但是,更改需要一些时间才能传播。要确定 Valkey 或 Redis OSS 集群的更改何时完全传播,请监视的输出。cluster slots一旦集群插槽命令返回的所有节点都使用新协议IPs进行报告,则更改已完成传播。

使用 Redis-Py 的示例:

cluster = RedisCluster(host="xxxx", port=6379) target_type = IPv6Address # Or IPv4Address if changing to IPv4 nodes = set() while len(nodes) == 0 or not all((type(ip_address(host)) is target_type) for host in nodes): nodes = set() # This refreshes the cluster topology and will discovery any node updates. # Under the hood it calls cluster slots cluster.nodes_manager.initialize() for node in cluster.get_nodes(): nodes.add(node.host) self.logger.info(nodes) time.sleep(1)

使用 Lettuce 的示例:

RedisClusterClient clusterClient = RedisClusterClient.create(RedisURI.create("xxxx", 6379)); Class targetProtocolType = Inet6Address.class; // Or Inet4Address.class if you're switching to IPv4 Set<String> nodes; do { // Check for any changes in the cluster topology. // Under the hood this calls cluster slots clusterClient.refreshPartitions(); Set<String> nodes = new HashSet<>(); for (RedisClusterNode node : clusterClient.getPartitions().getPartitions()) { nodes.add(node.getUri().getHost()); } Thread.sleep(1000); } while (!nodes.stream().allMatch(node -> { try { return finalTargetProtocolType.isInstance(InetAddress.getByName(node)); } catch (UnknownHostException ignored) {} return false; }));