Este conteúdo foi traduzido por máquina para sua conveniência e a Huawei Cloud não pode garantir que o conteúdo foi traduzido com precisão. Para exibir o conteúdo original, use o link no canto superior direito para mudar para a página em inglês.
Computação
Elastic Cloud Server
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Redes
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Gerenciamento e governança
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
Cloud Operations Center
Resource Governance Center
Migração
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Análises
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
IoT
IoT Device Access
Outros
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Segurança e conformidade
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Serviços de mídia
Media Processing Center
Video On Demand
Live
SparkRTC
Armazenamento
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Cloud Server Backup Service
Storage Disaster Recovery Service
Scalable File Service
Volume Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Bancos de dados
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Aplicações de negócios
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Data Lake Factory
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Distribuição de conteúdo e computação de borda
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Soluções
SAP Cloud
High Performance Computing
Serviços para desenvolvedore
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
Cloud Application Engine
MacroVerse aPaaS
KooPhone
KooDrive
Nesta página

Java

Atualizado em 2025-01-23 GMT+08:00

Acesse uma instância do DCS Memcached usando um cliente Java em um ECS na mesma VPC.

Pré-requisitos

  • A instância do Memcached DCS que você deseja acessar está no estado Running.
  • Foi criado um ECS no qual o cliente foi instalado. Para obter detalhes sobre como criar os ECS, consulte o Guia do usuário do Elastic Cloud Server.

    Um ECS pode se comunicar com uma instância de DCS que pertence à mesma VPC e está configurada com o mesmo grupo de segurança.

    • Se a instância do ECS e do DCS estiverem nas VPC diferentes, estabeleça uma conexão de peering de VPC para obter conectividade de rede entre o ECS e a instância do DCS. Para obter detalhes, consulte O DCS oferece suporte ao acesso entre VPC?
    • Se grupos de segurança diferentes tiverem sido configurados para a instância do ECS e do DCS, defina regras de grupo de segurança para obter conectividade de rede entre o ECS e a instância do DCS. Para obter detalhes, consulte Como configurar um grupo de segurança?
  • O kit de desenvolvimento Java (JDK) e ambientes de desenvolvimento integrados comuns (os IDE), como o Eclipse, foram instalados no ECS.
  • Você obteve o pacote de dependências spymemcached-x.y.z.jar.

    x.y.z indica a versão do pacote de dependência. Recomenda-se a versão mais recente.

Procedimento

  1. Efetue login no console de DCS.
  2. Clique em no canto superior esquerdo do console de gerenciamento e selecione uma região.

    Selecione a mesma região que o serviço do aplicativo.

  3. No painel de navegação, escolha Cache Manager.
  4. Na página Cache Manager, clique no nome da instância do Memcached DCS que deseja acessar. Obtenha o endereço IP ou o nome de domínio e o número da porta da instância.
  5. Carregue o pacote de dependências spymemcached-x.y.z.jar obtido no ECS criado.
  6. Acesse o ECS.
  7. Crie um projeto Java no Eclipse e importe o pacote de dependência spymemcached-x.y.z.jar. O nome do projeto é personalizável.
  8. Crie uma classe ConnectMemcached1, copie o seguinte código Java para a classe e modifique o código.

    • Exemplo de código para o modo de senha

      Alterar IP ou nome de domínio:porta para o endereço IP e o número da porta obtidos em 4. Definir Nome de usuário e Senha respectivamente para o nome de usuário e a senha da instância do Memcached.

      //Connect to the encrypted Memcached code using Java.
      import java.io.IOException;
      import java.util.concurrent.ExecutionException;
      
      import net.spy.memcached.AddrUtil;
      import net.spy.memcached.ConnectionFactoryBuilder;
      import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
      import net.spy.memcached.MemcachedClient;
      import net.spy.memcached.auth.AuthDescriptor;
      import net.spy.memcached.auth.PlainCallbackHandler;
      import net.spy.memcached.internal.OperationFuture;
      
      public class ConnectMemcached1
      {
          public static void main(String[] args)
          {
              final String connectionaddress = "
      									ip or domain name:port
      								"; 
              final String username = "
      									userName
      								";//Indicates the username.
              final String password = "
      									password
      								";//Indicates the password.
              MemcachedClient client = null;
              try
              {
                  AuthDescriptor authDescriptor =
                      new AuthDescriptor(new String[] {"PLAIN"}, new PlainCallbackHandler(username,
                              password));
                  client = new MemcachedClient(
                          new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)
                                  .setAuthDescriptor(authDescriptor)
                                  .build(),
                          AddrUtil.getAddresses(connectionaddress));
                  String key = "memcached";//Stores data with the key being memcached in Memcached.
                  String value = "Hello World";//The value is Hello World. 
                  int expireTime = 5; //Specifies the expiration time, measured in seconds. The countdown starts from the moment data is written. After the expireTime elapses, the data expires and can no longer be read.
                  doExcute(client, key, value, expireTime);//Executes the operation.
              }
              catch (IOException e)
              {
                  e.printStackTrace();
              }
          }
      
          /**
           *Method of writing data to Memcached
           */
          private static void doExcute(MemcachedClient client, String key, String value, int expireTime)
          {
              try
              {
                  OperationFuture<Boolean> future = client.set(key, expireTime, value);
                  future.get();//spymemcached set () is asynchronous. future.get () waits until the cache.set () operation is completed, or does not need to wait. You can select based on actual requirements.
                  System.out.println("The Set operation succeeded.");
                  System.out.println("Get operation:" + client.get(key));
                  Thread.sleep(6000);//Waits for 6000 ms, that is, 6s. Then the data expires and can no longer be read.
                  System.out.println("Perform the Get operation 6s later:" + client.get(key));
      
              }
              catch (InterruptedException e)
              {
                  e.printStackTrace();
              }
              catch (ExecutionException e)
              {
                  e.printStackTrace();
              }
              if (client != null)
              {
                  client.shutdown();
              }
          }
      }
    • Código de exemplo para o modo livre de senha

      Altere ip address or domain name:port para o endereço IP e o número da porta obtidos em 4.

      //Connect to the password-free Memcached code using Java.
      import java.io.IOException;
      import java.util.concurrent.ExecutionException;
      
      import net.spy.memcached.AddrUtil;
      import net.spy.memcached.BinaryConnectionFactory;
      import net.spy.memcached.MemcachedClient;
      import net.spy.memcached.internal.OperationFuture;
      
      public class ConnectMemcached
      {
          public static void main(String[] args)
          {
              final String connectionaddress = "ip or domain name:port"; 
              MemcachedClient client = null;
              try
              {
                  client = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(connectionaddress));
                  String key = "memcached";//Stores data with the key being memcached in Memcached.
                  String value = "Hello World";//The value is Hello World. 
                  int expireTime = 5; //Specifies the expiration time, measured in seconds. The countdown starts from the moment data is written. After the expireTime elapses, the data expires and can no longer be read.
                  doExcute(client, key, value, expireTime);//Executes the operation.
              }
              catch (IOException e)
              {
                  e.printStackTrace();
              }
          }
      
          /**
           *Method of writing data to Memcached
           */
          private static void doExcute(MemcachedClient client, String key, String value, int expireTime)
          {
              try
              {
                  OperationFuture<Boolean> future = client.set(key, expireTime, value);
                  future.get();//spymemcached set () is asynchronous. future.get () waits until the cache.set () operation is completed, or does not need to wait. You can select based on actual requirements.
                  System.out.println("The Set operation succeeded.");
                  System.out.println("Get operation:" + client.get(key));
                  Thread.sleep(6000);//Waits for 6000 ms, that is, 6s. Then the data expires and can no longer be read.
                  System.out.println("Perform the Get operation 6s later:" + client.get(key));
      
              }
              catch (InterruptedException e)
              {
                  e.printStackTrace();
              }
              catch (ExecutionException e)
              {
                  e.printStackTrace();
              }
              if (client != null)
              {
                  client.shutdown();
              }
          }
      }

  9. Execute o método main. O seguinte resultado é exibido na janela Console do Eclipse:

    The Set operation succeeded.
    Get operation: Hello World
    Perform the Get operation 6s later: null

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Conteúdo selecionado

Envie o conteúdo selecionado com o feedback