

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

# 使用 Auto Discovery
<a name="AutoDiscovery.Using"></a>

要开始将自动发现功能与 ElastiCache for Memcached 搭配使用，请按照以下步骤操作：
+ [获取配置端点](#AutoDiscovery.Using.ConfigEndpoint)
+ [下载 ElastiCache Cluster Client](#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 使用适用于 ElastiCache 的 AWS CLI 查找端点**  
对于 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 Cluster Client
<a name="AutoDiscovery.Using.ClusterClient"></a>

如要利用 Auto Discovery，客户端程序必须使用 *ElastiCache Cluster Client*。ElastiCache Cluster Client 可用于 Java、PHP 和 .NET，其中包含适用于发现和连接至您的所有缓存节点所需的全部逻辑。

**下载 ElastiCache Cluster Client**

1. 登录 AWS 管理控制台并打开 ElastiCache 控制台 ([https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/))。

1. 在 ElastiCache 控制台上，选择 **ElastiCache Cluster Client**，然后选择 **Download（下载）**。

ElastiCache Cluster Client for Java 的源代码可在 [https://github.com/amazonwebservices/aws-elasticache-cluster-client-memcached-for-java](https://github.com/amazonwebservices/aws-elasticache-cluster-client-memcached-for-java) 获取。此库是以常见的 Spymemcached 客户端为基础。ElastiCache Cluster Client 根据亚马逊软件许可 [https://aws.amazon.com/asl](https://aws.amazon.com/asl) 发布。您可以按照自己的方式自由修改源代码。您甚至可以将代码并入其他开放源 Memcached 库中或者您自己的客户端代码中。

**注意**  
如要使用适用于 PHP 的 ElastiCache Cluster Client，您首先需要将其安装在您的 Amazon EC2 实例上。有关更多信息，请参阅 [安装适用于 PHP 的 ElastiCache Cluster Client](Appendix.PHPAutoDiscoverySetup.md)。  
对于支持 TLS 的客户端，请下载 PHP 版本 7.4 或更高版本的二进制文件。  
若要使用适用于 .NET 的 ElastiCache Cluster Client，您首先需要将其安装在您的 Amazon EC2 实例上。有关更多信息，请参阅 [安装适用于 .NET 的 ElastiCache Cluster Client](Appendix.DotNETAutoDiscoverySetup.md)。

## 修改应用程序编程
<a name="AutoDiscovery.Using.ModifyApp"></a>

修改您的应用程序，以便它可以使用 Auto Discovery。以下部分介绍了如何使用适用于 Java、PHP 和 .NET 的 ElastiCache Cluster Client。

**重要**  
指定集群的配置终端节点时，请确保其地址中有 ".cfg"，如此处所示。请勿使用 CNAME 或其中没有 ".cfg" 的终端节点。  

```
"mycluster.fnjyzo.cfg.use1.cache.amazonaws.com";
```
 未明确指定集群的配置终端节点会导致配置到特定节点。

# 使用适用于 Java 的 ElastiCache Cluster Client
<a name="AutoDiscovery.Using.ModifyApp.Java"></a>

下述程序演示了如何使用 ElastiCache Cluster Client 以连接到集群配置端点，并将数据项目添加至缓存中。借助 Auto Discovery，程序可在没有任何进一步干预的情况下连接至集群中的所有节点。

```
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 集群客户端连接到集群配置终端节点并将数据项添加到缓存。借助 Auto Discovery，程序将在没有任何进一步干预的情况下连接至集群中的所有节点。

要使用适用于 PHP 的 ElastiCache 集群客户端，您首先需要将其安装在您的 Amazon EC2 实例上。有关更多信息，请参阅 [安装适用于 PHP 的 ElastiCache Cluster Client](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 Cluster Client
<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 Cluster Client 以连接到集群配置端点，并将数据项目添加至缓存中。借助 Auto Discovery，程序将在没有任何进一步干预的情况下连接至集群中的所有节点。

```
// *****************
// 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
```