本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
用戶端的最佳實務 (Valkey 和 Redis OSS)
了解常見案例的最佳實務,並遵循一些最熱門的開放原始碼 Valkey 和 Redis OSS 用戶端程式庫 (redis-py、PHPRedis 和 Lettuce) 的程式碼範例,以及與 ElastiCache 資源與常用開放原始碼 Memcached 用戶端程式庫互動的最佳實務。
主題
為雙堆疊叢集設定偏好的通訊協定 (Valkey 和 Redis OSS)
對於啟用叢集模式的 Valkey 或 Redis OSS 叢集,您可以使用 IP 探索參數控制通訊協定用戶端將用來連線至叢集中的節點。IP 探索參數可以設為 IPv4 或 IPv6。
對於 Valkey 或 Redis OSS 叢集,IP 探索參數會設定叢集插槽 ()
變更 IP 探索不會導致連線用戶端停機。但是,該變更需要一些傳播時間。若要判斷變更何時完全傳播至 Valkey 或 Redis OSS 叢集,請監控 的輸出cluster slots
。一旦叢集槽命令傳回的所有節點都報告了具新通訊協定的 IP,就表示變更已完成傳播。
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; }));