用戶端的最佳實務 (Valkey 和 RedisOSS) - Amazon ElastiCache

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

用戶端的最佳實務 (Valkey 和 RedisOSS)

了解常見案例的最佳實務,並遵循一些最熱門開放原始碼 Valkey 和 Redis OSS用戶端程式庫 (redis-pyPHPRedis、 和 Lettuce) 的程式碼範例,以及使用常用開放原始碼 Memcached 用戶端程式庫與 ElastiCache 資源互動的最佳實務。

為雙堆疊叢集設定偏好的通訊協定 (Valkey 和 RedisOSS)

對於啟用叢集模式的 Valkey 或 Redis OSS叢集,您可以控制通訊協定用戶端將使用 IP Discovery 參數連線到叢集中的節點。IP Discovery 參數可以設定為 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; }));