

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# キャッシュへのデータの読み取りと書き込み
<a name="read-write-cache-mem"></a>

このセクションでは、Amazon EC2 インスタンスが作成済みであり、このインスタンスに接続できることを前提としています。これを行う手順については、「[Amazon EC2 入門ガイド](https://aws.amazon.com/ec2/getting-started/)」を参照してください。

デフォルトで、ElastiCache はデフォルトの VPC でキャッシュを作成します。キャッシュに接続できるように、EC2 インスタンスもデフォルト VPC に作成されていることを確認します。

**キャッシュエンドポイントを検索する**

**AWS マネジメントコンソール**

ElastiCache コンソールを使用してキャッシュのエンドポイントを見つけるには:

1. にサインインAWS マネジメントコンソールし、[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/) で Amazon ElastiCache コンソールを開きます。

1. コンソールの左側のナビゲーションペインで、**[Memcached キャッシュ]** を選択します。

1. コンソールの右側で、作成したキャッシュの名前をクリックします。

1. **[キャッシュ詳細]** で、キャッシュエンドポイントを見つけてコピーします。

**AWS CLI**

次のAWS CLI例は、describe-serverless-caches コマンドを使用して新しいキャッシュのエンドポイントを検索する方法を示しています。コマンドを実行したら、「Endpoint」フィールドを探します。

**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\$1started.html](https://pymemcache.readthedocs.io/en/latest/getting_started.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 memcache) を使用して接続する
<a name="w2aac14c21c41c29b9"></a>

[https://github.com/electrode-io/memcache](https://github.com/electrode-io/memcache) と [https://www.npmjs.com/package/memcache-client](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-memcache](https://github.com/aisk/rust-memcache) を参照してください。

```
// 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/gomemcache ](https://github.com/bradfitz/gomemcache)を参照してください

```
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)」に進むことができます。