

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Leggi e scrivi dati nella cache
<a name="read-write-cache-mem"></a>

Questa sezione presuppone che sia stata creata un'istanza Amazon EC2 ed eseguita la connessione alla stessa. Per istruzioni su come procedere, consoluta la [Guida alle operazioni di base di Amazon EC2](https://aws.amazon.com/ec2/getting-started/). 

Per impostazione predefinita, ElastiCache crea una cache nel tuo VPC predefinito. Assicurati che anche l'istanza EC2 sia creata nel VPC predefinito, in modo da potersi connettere alla cache. 

**Ricerca dell'endpoint della cache**

**Console di gestione AWS**

Per trovare l'endpoint della cache utilizzando la ElastiCache console:

1. Accedi a Console di gestione AWS e apri la ElastiCache console Amazon all'indirizzo [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/). 

1. Nel riquadro di navigazione sul lato sinistro della console scegli **Cache Memcached**.

1. Sul lato destro della console fai clic sul nome della cache che hai appena creato. 

1. In **Dettagli della cache** individua e copia l'endpoint della cache. 

**AWS CLI**

L' AWS CLI esempio seguente mostra come trovare l'endpoint per la nuova cache utilizzando il comando describe-serverless-caches. Dopo aver eseguito il comando, cerca il campo "Endpoint". 

**Linux**

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

**Windows**

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

## Connessione tramite OpenSSL
<a name="w2aac14c21c41c29b1"></a>

 Per informazioni su come eseguire la connessione tramite OpenSSL, consulta [ElastiCache crittografia in transito (TLS)](in-transit-encryption.md).

## Connessione tramite il client Memcached Java
<a name="w2aac14c21c41c29b3"></a>

**Nota**  
[L'esempio seguente utilizza il fork del client spymemcached, AWS aws-elasticache-cluster-client-memcached-for-java.](https://github.com/awslabs/aws-elasticache-cluster-client-memcached-for-java) `setSSLContext`Il metodo è disponibile solo in questo fork e non fa parte della libreria standard open source 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.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");
    }
}
```

## Connessione tramite il client 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);
?>
```

## Connessione tramite il client Memcached Python (Pymemcache)
<a name="w2aac14c21c41c29b7"></a>

Per informazioni, consultare [https://pymemcache.readthedocs.io/en/latest/getting\_started.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"
```

## Connect tramite NodeJS/TS client Memcached (Electrode-IO memcache)
<a name="w2aac14c21c41c29b9"></a>

[https://github.com/electrode-io/memcache](https://github.com/electrode-io/memcache)Vedi e [https://www.npmjs.com/package/memcache-client](https://www.npmjs.com/package/memcache-client)

Installa usando `npm i memcache-client`.

Nell'applicazione, crea un client TLS Memcached come segue:

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

## Connessione tramite il client Memcached Rust (rust-memcache)
<a name="w2aac14c21c41c29c11"></a>

Consulta [https://crates.io/crates/memcache](https://crates.io/crates/memcache) e [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();
```

## Connessione tramite il client Memcached Go (Gomemcache)
<a name="w2aac14c21c41c29c13"></a>

Per informazioni, consultare [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)
```

## Connessione tramite il client Memcached Ruby (Dalli)
<a name="w2aac14c21c41c29c15"></a>

Per informazioni, consultare [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")
```

## Connect utilizzando il client Memcached .NET () EnyimMemcachedCore
<a name="w2aac14c21c41c29c17"></a>

Per informazioni, consultare [https://github.com/cnblogs/EnyimMemcachedCore](https://github.com/cnblogs/EnyimMemcachedCore).

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

Ora puoi procedere alla [(Facoltativo) Pulizia](read-write-cleanup-mem.md).