

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

# 使用自動探索
<a name="AutoDiscovery.Using"></a>

若要開始將 Auto Discovery 與 ElastiCache for Memcached 搭配使用，請遵循下列步驟：
+ [取得組態端點](#AutoDiscovery.Using.ConfigEndpoint)
+ [下載 ElastiCache 叢集用戶端](#AutoDiscovery.Using.ClusterClient)
+ [修改您的應用程式](#AutoDiscovery.Using.ModifyApp)

## 取得組態端點
<a name="AutoDiscovery.Using.ConfigEndpoint"></a>

為了連線到叢集，用戶端程式必須知道叢集的組態端點。請參閱主題：[尋找叢集的端點 （主控台） (Memcached)](Endpoints.md#Endpoints.Find.Memcached)

您也可以使用 `aws elasticache describe-cache-clusters` 命令搭配 `--show-cache-node-info` 參數：

無論您用來尋找叢集端點的方法為何，組態端點的地址內都會一律包含 **.cfg**。

**Example 使用 AWS CLI for ElastiCache 尋找端點**  
若為 Linux、macOS 或 Unix：  

```
aws elasticache describe-cache-clusters \
    --cache-cluster-id mycluster \
    --show-cache-node-info
```
針對 Windows：  

```
aws elasticache describe-cache-clusters ^
    --cache-cluster-id mycluster ^
    --show-cache-node-info
```
此作業會產生類似下列的輸出 (JSON 格式)：  

```
{
    "CacheClusters": [
        {
            "Engine": "memcached", 
            "CacheNodes": [
                {
                    "CacheNodeId": "0001", 
                    "Endpoint": {
                        "Port": 11211, 
                        "Address": "mycluster.fnjyzo.cfg.0001.use1.cache.amazonaws.com"
                    }, 
                    "CacheNodeStatus": "available", 
                    "ParameterGroupStatus": "in-sync", 
                    "CacheNodeCreateTime": "2016-10-12T21:39:28.001Z", 
                    "CustomerAvailabilityZone": "us-east-1e"
                }, 
                {
                    "CacheNodeId": "0002", 
                    "Endpoint": {
                        "Port": 11211, 
                        "Address": "mycluster.fnjyzo.cfg.0002.use1.cache.amazonaws.com"
                    }, 
                    "CacheNodeStatus": "available", 
                    "ParameterGroupStatus": "in-sync", 
                    "CacheNodeCreateTime": "2016-10-12T21:39:28.001Z", 
                    "CustomerAvailabilityZone": "us-east-1a"
                }
            ], 
            "CacheParameterGroup": {
                "CacheNodeIdsToReboot": [], 
                "CacheParameterGroupName": "default.memcached1.4", 
                "ParameterApplyStatus": "in-sync"
            }, 
            "CacheClusterId": "mycluster", 
            "PreferredAvailabilityZone": "Multiple", 
            "ConfigurationEndpoint": {
                "Port": 11211, 
                "Address": "mycluster.fnjyzo.cfg.use1.cache.amazonaws.com"
            }, 
            "CacheSecurityGroups": [], 
            "CacheClusterCreateTime": "2016-10-12T21:39:28.001Z", 
            "AutoMinorVersionUpgrade": true, 
            "CacheClusterStatus": "available", 
            "NumCacheNodes": 2, 
            "ClientDownloadLandingPage": "https://console.aws.amazon.com/elasticache/home#client-download:", 
            "CacheSubnetGroupName": "default", 
            "EngineVersion": "1.4.24", 
            "PendingModifiedValues": {}, 
            "PreferredMaintenanceWindow": "sat:06:00-sat:07:00", 
            "CacheNodeType": "cache.r3.large"
        }
    ]
}
```

## 下載 ElastiCache 叢集用戶端
<a name="AutoDiscovery.Using.ClusterClient"></a>

若要利用自動探索功能，用戶端程式必須使用 *ElastiCache 叢集用戶端*。ElastiCache 叢集用戶端適用於 Java、PHP 及 .NET，並包含探索及連線到所有快取節點的必要邏輯。

**下載 ElastiCache 叢集用戶端**

1. 登入 AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/) 開啟 ElastiCache 主控台。

1. 從 ElastiCache 主控台中，選擇 **ElastiCache Cluster Client (ElastiCache 叢集用戶端)**，然後選擇 **Download (下載)**。

如需適用於 Java 的 ElastiCache 叢集用戶端原始碼，請前往 [https://github.com/amazonwebservices/aws-elasticache-cluster-client-memcached-for-java](https://github.com/amazonwebservices/aws-elasticache-cluster-client-memcached-for-java)。此程式庫是以熱門的 Spymemcached 用戶端為基礎。ElastiCache 叢集用戶端是根據 Amazon 軟體授權 ([https://aws.amazon.com/asl](https://aws.amazon.com/asl)) 發行。您可以視需要自由修改來源碼。您甚至可以將程式碼併入其他開放原始碼 Memcached 程式庫，或是併入您自己的用戶端程式碼。

**注意**  
若要使用適用於 PHP 的 ElastiCache 叢集用戶端，您必須先在 Amazon EC2 執行個體上安裝它。如需詳細資訊，請參閱[安裝適用於 PHP 的 ElastiCache 叢集用戶端](Appendix.PHPAutoDiscoverySetup.md)。  
若為支援 TLS 的用戶端，請下載 PHP 7.4 或更高版本的二進位檔。  
若要使用適用於 .NET 的 ElastiCache 叢集用戶端，您必須先在 Amazon EC2 執行個體上安裝它。如需詳細資訊，請參閱[安裝適用於 .NET 的 ElastiCache 叢集用戶端](Appendix.DotNETAutoDiscoverySetup.md)。

## 修改您的應用程式
<a name="AutoDiscovery.Using.ModifyApp"></a>

修改您的應用程式以使用自動探索。以下各節示範如何使用適用於 Java、PHP 及 .NET 的 ElastiCache 叢集用戶端。

**重要**  
指定叢集的組態端點時，請務必確認端點的地址內包含 ".cfg"，如以下所示。請不要使用未包含 ".cfg" 的 CNAME 或端點。  

```
"mycluster.fnjyzo.cfg.use1.cache.amazonaws.com";
```
 明確指定叢集組態端點失敗，可能會導致設定至特定節點。

# 使用適用於 Java 的 ElastiCache 叢集用戶端
<a name="AutoDiscovery.Using.ModifyApp.Java"></a>

以下程式會示範如何使用 ElastiCache 叢集用戶端連線到叢集組態端點，然後將資料項目新增到快取。使用自動探索，程式便會連線到叢集內的所有節點，而不會進行其他介入。

```
package com.amazon.elasticache;

import java.io.IOException;
import java.net.InetSocketAddress;

// Import the &AWS;-provided library with Auto Discovery support 
import net.spy.memcached.MemcachedClient;  

public class AutoDiscoveryDemo {

    public static void main(String[] args) throws IOException {
            
        String configEndpoint = "mycluster.fnjyzo.cfg.use1.cache.amazonaws.com";
        Integer clusterPort = 11211;

        MemcachedClient client = new MemcachedClient(
                                 new InetSocketAddress(configEndpoint, 
                                                       clusterPort));       
        // The client will connect to the other cache nodes automatically.

        // Store a data item for an hour.  
        // The client will decide which cache host will store this item. 
        client.set("theKey", 3600, "This is the data value");
    }
}
```

# 使用適用於 PHP 的 ElastiCache 叢集用戶端
<a name="AutoDiscovery.Using.ModifyApp.PHP"></a>

以下程式會示範如何使用 ElastiCache 叢集用戶端連線到叢集組態端點，然後將資料項目新增到快取。使用自動探索，程式將會連線到叢集內的所有節點，而不會進行其他介入。

若要使用適用於 PHP 的 ElastiCache 叢集用戶端，您必須先在 Amazon EC2 執行個體上安裝它。如需詳細資訊，請參閱[安裝適用於 PHP 的 ElastiCache 叢集用戶端](Appendix.PHPAutoDiscoverySetup.md)

```
<?php
	
 /**
  * Sample PHP code to show how to integrate with the Amazon ElastiCache
  * Auto Discovery feature.
  */

  /* Configuration endpoint to use to initialize memcached client. 
   * This is only an example. 	*/
  $server_endpoint = "mycluster.fnjyzo.cfg.use1.cache.amazonaws.com";
  
  /* Port for connecting to the ElastiCache cluster. 
   * This is only an example 	*/
  $server_port = 11211;

 /**
  * The following will initialize a Memcached client to utilize the Auto Discovery feature.
  * 
  * By configuring the client with the Dynamic client mode with single endpoint, the
  * client will periodically use the configuration endpoint to retrieve the current cache
  * cluster configuration. This allows scaling the cluster up or down in number of nodes
  * without requiring any changes to the PHP application. 
  *
  * By default the Memcached instances are destroyed at the end of the request. 
  * To create an instance that persists between requests, 
  *    use persistent_id to specify a unique ID for the instance. 
  * All instances created with the same persistent_id will share the same connection. 
  * See [http://php.net/manual/en/memcached.construct.php](http://php.net/manual/en/memcached.construct.php) for more information.
  */
  $dynamic_client = new Memcached('persistent-id');
  $dynamic_client->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
  $dynamic_client->addServer($server_endpoint, $server_port);
  
  /**
  * Store the data for 60 seconds in the cluster. 
  * The client will decide which cache host will store this item.
  */  
  $dynamic_client->set('key', 'value', 60);  


 /**
  * Configuring the client with Static client mode disables the usage of Auto Discovery
  * and the client operates as it did before the introduction of Auto Discovery. 
  * The user can then add a list of server endpoints.
  */
  $static_client = new Memcached('persistent-id');
  $static_client->setOption(Memcached::OPT_CLIENT_MODE, Memcached::STATIC_CLIENT_MODE);
  $static_client->addServer($server_endpoint, $server_port);

 /**
  * Store the data without expiration. 
  * The client will decide which cache host will store this item.
  */  
  $static_client->set('key', 'value');  
  ?>
```

如需如何使用已啟用 TLS 的 ElastiCache 叢集用戶端範例，請參閱[使用傳輸中加密搭配 PHP 和 Memcached](in-transit-encryption.md#in-transit-encryption-connect-php-mc)。

# 使用適用於 .NET 的 ElastiCache 叢集用戶端
<a name="AutoDiscovery.Using.ModifyApp.DotNET"></a>

**注意**  
自 2022 年 5 月起，已淘汰 ElastiCache .NET 叢集用戶端。

適用於 ElastiCache 的 .NET 用戶端為開放原始碼資源，位於 [https://github.com/awslabs/elasticache-cluster-config-net](https://github.com/awslabs/elasticache-cluster-config-net)。

 .NET 應用程式通常會從其組態檔取得組態。以下是範例應用程式組態檔。

```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section 
            name="clusterclient" 
            type="Amazon.ElastiCacheCluster.ClusterConfigSettings, Amazon.ElastiCacheCluster" />
    </configSections>

    <clusterclient>
        <!-- the hostname and port values are from step 1 above -->
        <endpoint hostname="mycluster.fnjyzo.cfg.use1.cache.amazonaws.com" port="11211" />
    </clusterclient>
</configuration>
```

以下 C\$1 程式示範如何使用 ElastiCache 叢集用戶端連線到叢集組態端點，然後將資料項目新增到快取。使用自動探索，程式將會連線到叢集內的所有節點，而不會進行其他介入。

```
// *****************
// Sample C# code to show how to integrate with the Amazon ElastiCcache Auto Discovery feature.

using System;

using Amazon.ElastiCacheCluster;

using Enyim.Caching;
using Enyim.Caching.Memcached;

public class DotNetAutoDiscoveryDemo  {

    public static void Main(String[] args)  {
    
        // instantiate a new client.
        ElastiCacheClusterConfig config = new ElastiCacheClusterConfig();
        MemcachedClient memClient = new MemcachedClient(config);
        
        // Store the data for 3600 seconds (1hour) in the cluster. 
        // The client will decide which cache host will store this item.
        memClient.Store(StoreMode.Set, 3600, "This is the data value.");
        
    }  // end Main
    
}  // end class DotNetAutoDiscoverDemo
```