

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

# 用戶端的最佳實務 (Valkey 和 Redis OSS)
<a name="BestPractices.Clients.redis"></a>

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

**Topics**
+ [大量的連線 (Valkey 和 Redis OSS)](BestPractices.Clients.Redis.Connections.md)
+ [叢集用戶端探索和指數退避 (Valkey 和 Redis OSS)](BestPractices.Clients.Redis.Discovery.md)
+ [設定用戶端逾時 (Valkey 和 Redis OSS)](BestPractices.Clients.Redis.ClientTimeout.md)
+ [設定伺服器端閒置逾時 (Valkey 和 Redis OSS)](BestPractices.Clients.Redis.ServerTimeout.md)
+ [Lua 指令碼](BestPractices.Clients.Redis.LuaScripts.md)
+ [儲存大型複合項目 (Valkey 和 Redis OSS)](BestPractices.Clients.Redis.LargeItems.md)
+ [Lettuce 用戶端組態 (Valkey 和 Redis OSS)](BestPractices.Clients-lettuce.md)
+ [為雙堆疊叢集設定偏好的通訊協定 (Valkey 和 Redis OSS)](#network-type-configuring-dual-stack-redis)

## 為雙堆疊叢集設定偏好的通訊協定 (Valkey 和 Redis OSS)
<a name="network-type-configuring-dual-stack-redis"></a>

對於啟用叢集模式的 Valkey 或 Redis OSS 叢集，您可以控制通訊協定用戶端將使用 IP 探索參數連接到叢集中的節點。IP 探索參數可以設為 IPv4 或 IPv6。

對於 Valkey 或 Redis OSS 叢集，IP 探索參數會設定[叢集插槽 ()](https://valkey.io/commands/cluster-slots/)、[叢集碎片 ()](https://valkey.io/commands/cluster-shards/) 和[叢集節點 ()](https://valkey.io/commands/cluster-nodes/) 輸出中使用的 IP 通訊協定。用戶端會使用這些命令來探索叢集拓撲。用戶端會使用這些命令中的 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;
}));
```