

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

# 使用適用於 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");
    }
}
```

ElastiCache Serverless 快取一律啟用傳輸中加密 (TLS)。您也可以在節點型叢集上啟用 TLS。若要連線至已啟用 TLS 的快取，請使用 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" 的組態端點。