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

Jedis

Atualizado em 2022-11-08 GMT+08:00

Acesse uma instância do DCS Redis por meio de Jedis em um ECS na mesma VPC. Para obter mais informações sobre como usar outros clientes do Redis, visite o site oficial do Redis.

Pré-requisitos

  • Uma instância do DCS Redis foi criada e está no estado Running.
  • Foi criado um ECS. Para obter detalhes sobre como criar um ECS, consulte Comprando um ECS .
  • Se o ECS executar o SO de Linux, certifique-se de que o ambiente de compilação Java tenha sido instalado no ECS.

Procedimento

  1. Visualize o endereço IP/nome do domínio e o número da porta da instância do DCS Redis a ser acessada.

    Para obter detalhes, consulte Exibindo Detalhes da Instância .

  2. Acesse o ECS.
  3. Use o Maven para adicionar a seguinte dependência ao arquivo pom.xml:

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.1.1</version>
    </dependency>

  4. Acesse a instância do DCS usando Jedis.

    Obtenha o código fonte do cliente Jedi. Use um dos dois métodos a seguir para acessar uma instância do DCS Redis por meio de Jedis:
    • Conexão de Jedis Únicos
    • Piscina Jedis

    Exemplo de código:

    1. Exemplo de uso de Jedis para se conectar a uma instância DCS Redis de cluster de nó único, mestre/em espera ou proxy com uma única conexão
      //Creating a connection in password mode
       String host = "192.168.0.150"; 
       int port = 6379; 
       String pwd = "passwd"; 
      
       Jedis client = new Jedis(host, port); 
       client.auth(pwd);
       client.connect(); 
      //Run the SET command.
       String result = client.set("key-string", "Hello, Redis!"); 
       System.out.println( String.format("set command result:%s", result) );
      //Run the GET command.
       String value = client.get("key-string"); 
      System.out.println( String.format("get command result:%s", value) );
      
      //Creating a connection in password-free mode
       String host = "192.168.0.150"; 
       int port = 6379; 
      
       Jedis client = new Jedis(host, port); 
       client.connect(); 
      //Run the SET command.
       String result = client.set("key-string", "Hello, Redis!"); 
       System.out.println( String.format("set command result:%s", result) );
      //Run the GET command.
       String value = client.get("key-string"); 
       System.out.println( String.format("get command result:%s", value) );

      host indica o exemplo de endereço IP/nome de domínio da instância do DCS e a port indica o número da porta da instância do DCS. Para obter detalhes sobre como obter o endereço IP/nome do domínio e a porta, consulte 1. Altere o endereço IP/domínio e a porta conforme necessário. pwd indica a senha usada para fazer login na instância do DCS Redis escolhida. Essa senha é definida durante a criação da instância do DCS Redis.

    2. Exemplo de uso de Jedis para conexão a uma instância de cluster DCS Redis de nó único, principal/em espera ou proxy com pool de conexão
      //Generate configuration information of a Jedis pool
       String ip = "192.168.0.150"; 
       int port = 6379; 
       String pwd = "passwd"; 
       GenericObjectPoolConfig config = new GenericObjectPoolConfig(); 
       config.setTestOnBorrow(false); 
       config.setTestOnReturn(false); 
       config.setMaxTotal(100); 
       config.setMaxIdle(100); 
       config.setMaxWaitMillis(2000); 
      JedisPool pool = new JedisPool(config, ip, port, 100000, pwd);//Generate a Jedis pool when the application is being initialized
      //Get a Jedis connection from the Jedis pool when a service operation occurs
       Jedis client = pool.getResource(); 
       try { 
           //Run commands
           String result = client.set("key-string", "Hello, Redis!"); 
           System.out.println( String.format("set command result:%s", result) ); 
           String value = client.get("key-string"); 
           System.out.println( String.format("get command result:%s", value) ); 
       } catch (Exception e) { 
           // TODO: handle exception
       } finally { 
           //Return the Jedis connection to the Jedis pool when the service operation is completed
           if (null != client) { 
               pool.returnResource(client); 
           } 
       } // end of try block
       //Destroy the Jedis pool when the application is closed
       pool.destroy();
      
      //Configure the connection pool in password-free mode
       String ip = "192.168.0.150"; 
       int port = 6379; 
       GenericObjectPoolConfig config = new GenericObjectPoolConfig(); 
       config.setTestOnBorrow(false); 
       config.setTestOnReturn(false); 
       config.setMaxTotal(100); 
       config.setMaxIdle(100); 
       config.setMaxWaitMillis(2000); 
       JedisPool pool = new JedisPool(config, ip, port, 100000);//Generate a JedisPool when the application is being initialized
       //Get a Jedis connection from the Jedis pool when a service operation occurs
       Jedis client = pool.getResource(); 
       try { 
           //Run commands
           String result = client.set("key-string", "Hello, Redis!"); 
           System.out.println( String.format("set command result:%s", result) ); 
           String value = client.get("key-string"); 
           System.out.println( String.format("get command result:%s", value) ); 
       } catch (Exception e) { 
           // TODO: handle exception
       } finally { 
           //Return the Jedis connection to the Jedis pool when the service operation is completed
           if (null != client) { 
               pool.returnResource(client); 
           } 
       } // end of try block
       //Destroy the Jedis pool when the application is closed
       pool.destroy();

      ip indica o endereço IP/nome de domínio da instância DCS e port indica o número da porta da instância DCS. Para obter detalhes sobre como obter o endereço IP/nome do domínio e a porta, consulte 1. Altere o endereço de IP/domínio e a porta conforme necessário. pwd indica a senha usada para fazer login na instância do DCS Redis escolhida. Essa senha é definida durante a criação da instância do DCS Redis.

    3. Exemplo de código para conexão com o Cluster do Redis usando uma única conexão
      • Com uma senha
        //The following shows password-protected access.
        int port = 6379;
        String host = "192.168.144.37";
        //Create JedisCluster.
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        nodes.add(new HostAndPort(host, port));
        JedisCluster cluster = new JedisCluster(nodes, 5000, 3000, 10, "password", new JedisPoolConfig());
        cluster.set("key", "value");
        System.out.println("Connected to RedisCluster:" + cluster.get("key"));
        cluster.close();
      • Sem uma senha
        int port = 6379;
        String host = "192.168.144.37";
        //Create JedisCluster.
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        nodes.add(new HostAndPort(host, port));
        JedisCluster cluster = new JedisCluster(nodes);
        cluster.set("key", "value");
        System.out.println("Connected to RedisCluster:" + cluster.get("key"));
        cluster.close();

      host indica o exemplo de endereço IP/nome de domínio da instância do DCS e a port indica o número da porta da instância do DCS. Para obter detalhes sobre como obter o endereço IP/nome do domínio e a porta, consulte 1. Altere o endereço IP/domínio e a porta conforme necessário. password indica a senha usada para fazer login na instância do DCS Redis escolhida. Essa senha é definida durante a criação da instância do DCS Redis.

  5. Compile o código de acordo com o arquivo readme no código fonte do cliente Jedis. Execute o cliente Jedis para acessar a instância do DCS Redis escolhida.

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