

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

# 对缓存读取和写入数据
<a name="read-write-cache-mem"></a>

本节假设您已经创建了一个 Amazon EC2 实例并且可以连接到该实例。有关如何执行此操作的说明，请参阅《[Amazon EC2 入门指南》](https://aws.amazon.com/ec2/getting-started/)。

默认情况下，在您的默认 VPC 中 ElastiCache 创建缓存。确保您的 EC2 实例也是在默认 VPC 中创建的，以便它能够连接到缓存。

**查找缓存端点**

**AWS 管理控制台**

要使用 ElastiCache 控制台查找缓存的终端节点，请执行以下操作：

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

1. 在控制台左侧的导航窗格中，选择 **Memcached 缓存**。

1. 在控制台的右侧，单击刚刚创建的缓存的名称。

1. 在**缓存详细信息**中，找到并复制缓存端点。

**AWS CLI**

以下AWS CLI示例说明如何使用 describe-serverless-caches命令查找新缓存的终端节点。运行命令后，查找“端点”字段。

**Linux**

```
aws elasticache describe-serverless-caches \
		--serverless-cache-name CacheName
```

**Windows**

```
aws elasticache describe-serverless-caches ^
		--serverless-cache-name CacheName
```

## 使用 OpenSSL 进行连接
<a name="w2aac14c21c41c29b1"></a>

 有关如何使用 OpenSSL 进行连接的信息，请参阅 [ElastiCache 传输中加密 (TLS)](in-transit-encryption.md)

## 使用 Memcached Java 客户端进行连接
<a name="w2aac14c21c41c29b3"></a>

```
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.FailureMode;
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);
        // Set Failure Mode to Retry
        connectionFactoryBuilder.setFailureMode(FailureMode.Retry);
        MemcachedClient client = new MemcachedClient(connectionFactoryBuilder.build(), AddrUtil.getAddresses("mycluster-fnjyzo.serverless.use1.cache.amazonaws.com:11211"));

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

## 使用 Memcached PHP 客户端进行连接
<a name="w2aac14c21c41c29b5"></a>

```
<?php
$cluster_endpoint = "mycluster.serverless.use1.cache.amazonaws.com";
$server_port = 11211; 

/* Initialize a persistent Memcached client in TLS mode */
$tls_client = new Memcached('persistent-id');
$tls_client->addServer($cluster_endpoint, $server_port);
if(!$tls_client->setOption(Memcached::OPT_USE_TLS, 1)) {
    echo $tls_client->getLastErrorMessage(), "\n";
    exit(1);
}
$tls_config = new MemcachedTLSContextConfig();
$tls_config->hostname = '*.serverless.use1.cache.amazonaws.com';
$tls_config->skip_cert_verify = false;
$tls_config->skip_hostname_verify = false;
$tls_client->createAndSetTLSContext((array)$tls_config); 

 /* store the data for 60 seconds in the cluster */
$tls_client->set('key', 'value', 60);
?>
```

## 使用 Memcached Python 客户端（Pymemcache）进行连接
<a name="w2aac14c21c41c29b7"></a>

请参阅 [https://pymemcache.readthedocs。 io/en/latest/getting](https://pymemcache.readthedocs.io/en/latest/getting_started.html)\$1started.html

```
import ssl
from pymemcache.client.base import Client
		
context = ssl.create_default_context()
cluster_endpoint = <To be taken from the AWS CLI / console>
target_port = 11211
memcached_client = Client(("{cluster_endpoint}", target_port), tls_context=context)
memcached_client.set("key", "value", expire=500, noreply=False)
assert self.memcached_client.get("key").decode() == "value"
```

## 使用 Memcached NodeJS/TS 客户端（Electrode-IO 内存缓存）连接
<a name="w2aac14c21c41c29b9"></a>

[参见[https://github.com/electrode-io/内存缓存和内存缓存](https://github.com/electrode-io/memcache)客户端 https://www.npmjs.com/package/](https://www.npmjs.com/package/memcache-client)

通过 `npm i memcache-client` 进行安装

在应用程序中，按以下所示创建 memcached TLS 客户端：

```
var memcache = require("memcache-client");
const client = new memcache.MemcacheClient({server: "{cluster_endpoint}:11211", tls: {}});
client.set("key", "value");
```

## 使用 Memcached Rust 客户端（rust-memcache）进行连接
<a name="w2aac14c21c41c29c11"></a>

见 [https://crates。 io/crates/memcache](https://crates.io/crates/memcache)还有 [https://github.com/aisk/rust-memcach](https://github.com/aisk/rust-memcache) e。

```
// create connection with to memcached server node:
let client = memcache::connect("memcache+tls://<cluster_endpoint>:11211?verify_mode=none").unwrap();
				
// set a string value
client.set("foo", "bar", 0).unwrap();
```

## 使用 Memcached Go 客户端（Gomemcache）进行连接
<a name="w2aac14c21c41c29c13"></a>

见 [https://github.com/bradfitz/gomemcach](https://github.com/bradfitz/gomemcache) e

```
c := New(net.JoinHostPort("{cluster_endpoint}", strconv.Itoa(port)))
c.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var td tls.Dialer
td.Config = &tls.Config{}
return td.DialContext(ctx, network, addr)
}
foo := &Item{Key: "foo", Value: []byte("fooval"), Flags: 123}
err := c.Set(foo)
```

## 使用 Memcached Ruby 客户端（Dalli）进行连接
<a name="w2aac14c21c41c29c15"></a>

见 [https://github.com/petergoldstein/dalli](https://github.com/petergoldstein/dalli)

```
require 'dalli'
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.ssl_version = :SSLv23
ssl_context.verify_hostname = true
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER
client = Dalli::Client.new("<cluster_endpoint>:11211", :ssl_context => ssl_context); 
client.get("abc")
```

## 使用 Memcached .NET 客户端连接 () EnyimMemcachedCore
<a name="w2aac14c21c41c29c17"></a>

请参阅 [https://github.com/cnblogs/EnyimMemcachedCore](https://github.com/cnblogs/EnyimMemcachedCore)。

```
"MemcachedClient": {
"Servers": [
{
"Address": "{cluster_endpoint}",
"Port": 11211
}
],
"UseSslStream":  true
}
```

您现在可以继续执行[（可选）清理](read-write-cleanup-mem.md)。