

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

# 使用适用于 Java 的 ElastiCache 群集客户端
<a name="AutoDiscovery.Using.ModifyApp.Java"></a>

以下程序演示了如何使用 ElastiCache 群集客户端连接到群集配置终端节点以及向缓存中添加数据项。借助 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");
    }
}
```

ElastiCache 无服务器缓存始终启用传输加密 (TLS)。您还可以在基于节点的集群上启用 TLS。要连接到 TLS-enabled缓存，请使用 SSLContext 配置客户端，如以下示例所示。

**注意**  
该`setSSLContext`方法仅在spymemcached客户端的 AWS 分支中可用。有关来源，请参见[aws-elasticache-cluster-client-memcached-for-java](https://github.com/awslabs/aws-elasticache-cluster-client-memcached-for-java)GitHub网站。此方法不是标准开源spymemcached库的一部分。

```
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
public class TLSDemo {
    public static void main(String[] args) throws Exception {
        ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder();
        // Build SSLContext
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        // Create the client in TLS mode
        connectionFactoryBuilder.setSSLContext(sslContext);
        MemcachedClient client = new MemcachedClient(connectionFactoryBuilder.build(), AddrUtil.getAddresses("mycluster.fnjyzo.cfg.use1.cache.amazonaws.com:11211"));

        // Store a data item for an hour.
        client.set("theKey", 3600, "This is the data value");
    }
}
```

有关使用 TLS 连接的更多信息，请参阅[使用 Java 创建 TLS Memcached 客户端](in-transit-encryption.md#in-transit-encryption-connect-java)。对于无服务器缓存，请在端口 11211 上使用缓存的无服务器端点。无服务器端点的地址中不包含 “.cfg”。对于启用 TLS 的基于节点的集群，使用包含 “.cfg” 的配置终端节点。