As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Ler e gravar dados no cache
Esta seção supõe que você tenha criado uma instância do Amazon EC2 e possa conectar-se a ela. Para obter instruções sobre como fazer isso, consulte o Guia de conceitos básicos do Amazon EC2
Por padrão, ElastiCache cria um cache na sua VPC padrão. Verifique se a instância do EC2 também foi criada na VPC padrão, para que ela possa se conectar ao cache.
Encontre o endpoint do cache
Console de gerenciamento da AWS
Para encontrar o endpoint do seu cache usando o ElastiCache console:
Faça login no Console de gerenciamento da AWS e abra o ElastiCache console da Amazon em https://console.aws.amazon.com/elasticache/
. No painel de navegação, no lado esquerdo do console, escolha Caches do Memcached.
No lado direito do console, clique no nome do cache que você acabou de criar.
Nos Detalhes do cache, localize e copie o endpoint do cache.
AWS CLI
O AWS CLI exemplo a seguir mostra como encontrar o endpoint para seu novo cache usando o comando describe-serverless-caches. Depois de executar o comando, procure o campo “Endpoint”.
Linux
aws elasticache describe-serverless-caches \ --serverless-cache-name CacheName
Windows
aws elasticache describe-serverless-caches ^ --serverless-cache-name CacheName
Para obter informações sobre como se conectar usando o OpenSSL, consulte ElastiCache criptografia em trânsito (TLS).
nota
O exemplo a seguir usa a bifurcação do cliente spymemcached, AWS aws-elasticache-cluster-client-memcached-for-java.setSSLContext método só está disponível nessa bifurcação e não faz parte da biblioteca spymemcached padrão de código aberto.
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"); } }
<?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); ?>
Consulte 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"
Consulte https://github.com/electrode-io/memcache
Instalar por meio de npm i memcache-client
Na aplicação, crie um cliente TLS do Memcached assim:
var memcache = require("memcache-client"); const client = new memcache.MemcacheClient({server: "{cluster_endpoint}:11211", tls: {}}); client.set("key", "value");
Consulte https://crates.io/crates/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();
Consulte 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)
Consulte 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")
Consulte https://github.com/cnblogs/EnyimMemcachedCore
"MemcachedClient": { "Servers": [ { "Address": "{cluster_endpoint}", "Port": 11211 } ], "UseSslStream": true }
Agora você já pode avançar para Limpar (opcional).