Todos os produtos
Search
Central de documentação

Tair (Redis® OSS-Compatible):Conecte-se a uma instância usando código de cliente

Última atualização: Aug 20, 2026

As instâncias do Tair (compatíveis com Redis OSS) são totalmente compatíveis com o Redis open-source. Conecte-se usando qualquer cliente compatível com Redis da mesma forma que você se conecta a um banco de dados Redis.

Pré-requisitos

Conclua as etapas a seguir com base no local onde seu cliente é executado.

Se o seu cliente for executado em uma instância ECS (recomendado):

  1. Certifique-se de que a instância do Elastic Compute Service (ECS) e a instância do Tair estejam na mesma virtual private cloud (VPC). As instâncias estão na mesma VPC se seus IDs de VPC coincidirem.

    Nota

    Se as instâncias estiverem em VPCs diferentes, altere a VPC da instância ECS. Se a instância ECS estiver na rede clássica e a instância Tair estiver em uma VPC, consulte Conectar uma instância ECS a uma instância Redis quando elas estiverem em tipos de rede diferentes.

  2. Obter o endereço IP interno da instância ECS.

  3. Adicionar o endereço IP privado da instância ECS à lista de permissões.

Se o seu cliente for executado localmente:

  1. Obtenha o endereço IP público da sua máquina:

    • Linux / macOS: Execute curl ifconfig.me no terminal.

    • Windows: Execute curl ip.me no Prompt de Comando.

  2. Adicionar o endereço IP público à lista de permissões da instância Tair.

  3. Solicitar um endpoint público. Por padrão, as instâncias do Tair fornecem apenas endpoints internos.

Observações de uso

  • Arquiteturas de cluster e de divisão de leitura/escrita: Ambas fornecem um endpoint de nó proxy por padrão. Conecte-se a essas instâncias da mesma maneira que você se conecta a uma instância de arquitetura padrão.

    Ao se conectar via endpoint de conexão direta , use o mesmo método utilizado para se conectar a um cluster Redis open-source.
  • Acesso sem senha: Se o acesso sem senha via VPC estiver ativado, os clientes na mesma VPC podem se conectar sem senha.

Obtenha informações de conexão

Antes de escrever o código, reúna os seguintes detalhes de conexão na página Instances. Selecione sua região na barra de navegação superior, clique em ID da instância e acesse a seção Connection Information.

Detalhe

Como obter

Endpoint

Visualize os endpoints e portas na seção Connection Information. Use endpoints de VPC para maior segurança e menor latência. Consulte Visualizar endpoints.

Porta

O padrão é 6379. Para alterá-la, consulte Alterar um endpoint ou porta.

Conta

Por padrão, cada instância possui uma conta com o nome igual ao ID da instância (por exemplo, r-bp10noxlhcoim2****). Para criar contas adicionais, consulte Criar e gerenciar contas.

Senha

O formato depende do tipo de conta: conta padrão — insira a senha diretamente; conta personalizada — use <username>:<password> (por exemplo, testaccount:Rp829dlwa).

Ao usar ferramentas de terceiros, como o Remote Desktop Manager (RDM), insira a senha no formato username:password . Para redefinir uma senha esquecida, consulte Alterar ou redefinir a senha .

Escolha um cliente

Escolha o cliente adequado para a sua linguagem. Todos os exemplos na próxima seção conectam-se à mesma instância do Tair.

Linguagem

Cliente

Estilo de API

Observações

Java

Jedis

Síncrono

Pool de conexões via JedisPool

Java

Lettuce

Assíncrono e reativo

Use a versão 6.3.0.RELEASE ou posterior

Java

Spring Data Redis

Síncrono ou assíncrono

Suporta backends Jedis e Lettuce

Python

redis-py

Síncrono

Cliente oficial para Python

Node.js

node-redis

Assíncrono

Cliente oficial para Node.js

Go

go-redis

Síncrono

Cliente Go amplamente utilizado

PHP

PhpRedis

Síncrono

Extensão C para PHP

C / C++

hiredis

Síncrono

Cliente C minimalista

.NET

StackExchange.Redis

Síncrono

Use a versão 2.7.20 ou posterior

Para a lista completa de clientes suportados, consulte Redis Clients.

Importante

Não utilize os clientes ServiceStack Redis ou CSRedis. Problemas com o ServiceStack Redis exigem a compra de suporte diretamente da ServiceStack, e o suporte ao CSRedis foi encerrado.

Conecte-se e teste

Os exemplos a seguir mostram o código mínimo necessário para conectar e executar um comando SET/GET. Substitua todos os valores de espaço reservado pelos seus detalhes reais de conexão.

Jedis

Este exemplo usa Jedis 4.3.0.

Este exemplo utiliza Maven. Você também pode baixar o JAR do Jedis diretamente.

  1. Adicione a dependência ao arquivo pom.xml:

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  2. Conecte-se e execute comandos:

    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    public class JedisExample {
        public static void main(String[] args) {
            JedisPoolConfig config = new JedisPoolConfig();
            // Max idle connections — must not exceed the instance's connection limit
            config.setMaxIdle(200);
            // Max total connections — must not exceed the instance's connection limit
            config.setMaxTotal(300);
            config.setTestOnBorrow(false);
            config.setTestOnReturn(false);
    
            // Replace with your instance endpoint and password
            String host = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com";
            // Default account: enter password directly
            // Custom account: use "username:password" format
            String password = "r-bp1s1bt2tlq3p1****:Database123";
    
            JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                jedis.set("foo10", "bar");
                System.out.println(jedis.get("foo10"));
                jedis.zadd("sose", 0, "car");
                jedis.zadd("sose", 0, "bike");
                System.out.println(jedis.zrange("sose", 0, -1));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
            // Call this when shutting down your application to release resources
            pool.destroy();
        }
    }
  3. Saída esperada:

    bar
    [bike, car]
Importante

Para erros no Jedis causados por parâmetros inválidos ou uso inadequado de recursos, consulte Erros comuns.

Lettuce

Este exemplo usa Lettuce 6.3.0.RELEASE.

Importante

Use Lettuce 6.3.0.RELEASE ou posterior e defina o parâmetro TCP_USER_TIMEOUT. Isso evita problemas de filtragem blackhole no cliente Lettuce.

Este exemplo utiliza Maven. Você também pode baixar o JAR do Lettuce diretamente.

  1. Adicione as seguintes dependências ao arquivo pom.xml:

    <dependencies>
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>6.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-transport-native-epoll</artifactId>
            <version>4.1.100.Final</version>
            <classifier>linux-x86_64</classifier>
        </dependency>
    </dependencies>
  2. Conecte-se e execute comandos:

    import io.lettuce.core.ClientOptions;
    import io.lettuce.core.RedisClient;
    import io.lettuce.core.RedisURI;
    import io.lettuce.core.SocketOptions;
    import io.lettuce.core.SocketOptions.KeepAliveOptions;
    import io.lettuce.core.SocketOptions.TcpUserTimeoutOptions;
    import io.lettuce.core.api.StatefulRedisConnection;
    import io.lettuce.core.api.sync.RedisCommands;
    import java.time.Duration;
    
    public class LettuceExample {
        /**
         * Enable TCP keepalive with these settings:
         *   TCP_KEEPIDLE  = 30 seconds
         *   TCP_KEEPINTVL = 10 seconds
         *   TCP_KEEPCNT   = 3
         */
        private static final int TCP_KEEPALIVE_IDLE = 30;
    
        /**
         * TCP_USER_TIMEOUT prevents Lettuce from getting stuck in a timeout loop
         * during a failure or crash. See: https://github.com/lettuce-io/lettuce-core/issues/2082
         */
        private static final int TCP_USER_TIMEOUT = 30;
    
        private static RedisClient client = null;
        private static StatefulRedisConnection<String, String> connection = null;
    
        public static void main(String[] args) {
            // Replace with your actual instance information
            String host     = "r-bp1s1bt2tlq3p1****.redis.rds.aliyuncs.com";
            String user     = "r-bp1s1bt2tlq3p1****";
            String password = "Da****3";
            int    port     = 6379;
    
            // Build RedisURI
            RedisURI uri = RedisURI.Builder
                    .redis(host, port)
                    .withAuthentication(user, password)
                    .build();
    
            // Configure TCP keepalive and TCP_USER_TIMEOUT
            SocketOptions socketOptions = SocketOptions.builder()
                    .keepAlive(KeepAliveOptions.builder()
                            .enable()
                            .idle(Duration.ofSeconds(TCP_KEEPALIVE_IDLE))
                            .interval(Duration.ofSeconds(TCP_KEEPALIVE_IDLE / 3))
                            .count(3)
                            .build())
                    .tcpUserTimeout(TcpUserTimeoutOptions.builder()
                            .enable()
                            .tcpUserTimeout(Duration.ofSeconds(TCP_USER_TIMEOUT))
                            .build())
                    .build();
    
            client = RedisClient.create(uri);
            client.setOptions(ClientOptions.builder()
                    .socketOptions(socketOptions)
                    .build());
    
            connection = client.connect();
            RedisCommands<String, String> commands = connection.sync();
    
            System.out.println(commands.set("foo", "bar"));
            System.out.println(commands.get("foo"));
    
            // Shut down — closes the connection and releases resources
            connection.close();
            client.shutdown();
        }
    }
  3. Saída esperada:

    OK
    bar

Spring Data Redis

Este exemplo usa Spring Data Redis 2.4.2.

Importante

Use a versão 6.3.0.RELEASE ou posterior do Lettuce e defina TCP_USER_TIMEOUT para evitar problemas de filtragem blackhole.

Este exemplo usa Maven com Lettuce ou Jedis como backend de conexão.

  1. Adicione o seguinte ao arquivo pom.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.2</version>
            <relativePath/>
        </parent>
        <groupId>com.aliyun.tair</groupId>
        <artifactId>spring-boot-example</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-boot-example</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
            <dependency>
                <groupId>io.lettuce</groupId>
                <artifactId>lettuce-core</artifactId>
                <version>6.3.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-transport-native-epoll</artifactId>
                <version>4.1.100.Final</version>
                <classifier>linux-x86_64</classifier>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
  2. Configure a fábrica de conexões. Escolha Jedis ou Lettuce: Spring Data Redis com Jedis:

    @Bean
    JedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", port);
    
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // Max total connections — must not exceed the instance's connection limit
        jedisPoolConfig.setMaxTotal(30);
        // Max idle connections — must not exceed the instance's connection limit
        jedisPoolConfig.setMaxIdle(20);
        // Disable testOn[Borrow|Return] to avoid extra PING commands
        jedisPoolConfig.setTestOnBorrow(false);
        jedisPoolConfig.setTestOnReturn(false);
    
        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder()
            .usePooling()
            .poolConfig(jedisPoolConfig)
            .build();
    
        return new JedisConnectionFactory(config, jedisClientConfiguration);
    }

    Spring Data Redis com Lettuce (inclui TCP_USER_TIMEOUT):

    @Configuration
    public class BeanConfig {
        /**
         * Enable TCP keepalive with these settings:
         *   TCP_KEEPIDLE  = 30 seconds
         *   TCP_KEEPINTVL = 10 seconds
         *   TCP_KEEPCNT   = 3
         */
        private static final int TCP_KEEPALIVE_IDLE = 30;
    
        /**
         * TCP_USER_TIMEOUT prevents Lettuce from getting stuck in a timeout loop
         * during a failure or crash. See: https://github.com/lettuce-io/lettuce-core/issues/2082
         */
        private static final int TCP_USER_TIMEOUT = 30;
    
        @Bean
        LettuceConnectionFactory redisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName("r-bp1y4is8svonly****pd.redis.rds.aliyuncs.com");
            config.setPort(6379);
            config.setUsername("r-bp1y4is8svonly****");
            config.setPassword("Da****3");
    
            SocketOptions socketOptions = SocketOptions.builder()
                .keepAlive(KeepAliveOptions.builder()
                    .enable()
                    .idle(Duration.ofSeconds(TCP_KEEPALIVE_IDLE))
                    .interval(Duration.ofSeconds(TCP_KEEPALIVE_IDLE / 3))
                    .count(3)
                    .build())
                .tcpUserTimeout(TcpUserTimeoutOptions.builder()
                    .enable()
                    .tcpUserTimeout(Duration.ofSeconds(TCP_USER_TIMEOUT))
                    .build())
                .build();
    
            LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
                .clientOptions(ClientOptions.builder().socketOptions(socketOptions).build())
                .build();
    
            return new LettuceConnectionFactory(config, lettuceClientConfiguration);
        }
    
        @Bean
        RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(connectionFactory);
            return template;
        }
    }
  3. Execute o código.

redis-py

Este exemplo usa Python 3.9 e redis-py 4.4.1.

  1. Baixe e instale o cliente redis-py.

  2. Conecte-se e execute comandos:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import redis
    
    # Replace with your instance endpoint and port
    host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    # Default account: enter password directly
    # Custom account: use "username:password" format
    pwd = 'testaccount:Rp829dlwa'
    
    r = redis.Redis(host=host, port=port, password=pwd)
    r.set('foo', 'bar')
    print(r.get('foo'))
  3. Execute o script.

node-redis

Este exemplo usa Node.js 19.4.0 e node-redis 4.5.1.

  1. Baixe e instale o node-redis.

  2. Conecte-se e execute comandos:

    import { createClient } from 'redis';
    
    // Replace with your instance endpoint, port, account, and password
    const host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com';
    const port = 6379;
    const username = 'testaccount';
    // If the password contains special characters (!@#$%^&*()+-=_), encode it first:
    // password = encodeURIComponent(password)
    const password = 'Rp829dlwa';
    
    const client = createClient({
      // redis://[[username]:[password]@[host][:port]/[db-number]
      url: `redis://${username}:${password}@${host}:${port}/0`
    });
    
    client.on('error', (err) => console.log('Redis Client Error', err));
    
    await client.connect();
    
    await client.set('foo', 'bar');
    const value = await client.get('foo');
    console.log("get foo: %s", value);
    
    await client.disconnect();
  3. Execute o script.

Se você encontrar SyntaxError: Cannot use import statement outside a module , renomeie o arquivo de .js para .mjs e execute-o com node --experimental-modules redis.mjs .

go-redis

Este exemplo usa Go 1.21 e go-redis v9.18.0. Em ambientes de produção, é crucial ajustar as configurações do pool de conexões (PoolSize, MinIdleConns) para atender às demandas de concorrência da sua aplicação e aos limites de conexão da sua instância Redis.

  1. Baixe e instale o cliente go-redis.

  2. Conecte-se e execute comandos:

    package main
    
    import (
    	"context"
    	"fmt"
    	"time"
    
    	"github.com/redis/go-redis/v9"
    )
    
    var ctx = context.Background()
    
    func ExampleClient() {
    	client := redis.NewClient(&redis.Options{
    		// Replace with your instance endpoint and port.
    		Addr: "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
    		// Replace with your instance password.
    		Password: "testaccount:Rp829dlwa",
    		DB:       0, // Use the default DB.
    
    		// Connection pool settings. Tune these for your workload, and do not exceed the instance's maximum connection limit.
    		PoolSize:     20,              // Maximum number of connections. Suggested value: peak QPS / per-connection QPS, or roughly 10 x CPU cores.
    		MinIdleConns: 5,               // Minimum idle connections. Pre-warms the pool to absorb traffic spikes without new dials.
    		PoolTimeout:  4 * time.Second, // Wait time when borrowing a connection from the pool. Set slightly larger than ReadTimeout.
    		ConnMaxIdleTime:  5 * time.Minute, // Idle connection close time. Must be less than the instance's idle timeout (default 600 seconds).
    
    		// Network and retry settings.
    		DialTimeout:  5 * time.Second, // Timeout for establishing the TCP connection.
    		ReadTimeout:  3 * time.Second, // Read timeout. -1 disables the timeout, 0 uses the default.
    		WriteTimeout: 3 * time.Second, // Write timeout.
    		MaxRetries:   3,               // Number of command retries on failure. -1 disables retries.
    	})
    	defer client.Close()
    
    	// The following code shows a SET/GET example.
    	if err := client.Set(ctx, "foo", "bar", 0).Err(); err != nil {
    		panic(err)
    	}
    
    	val, err := client.Get(ctx, "foo").Result()
    	if err != nil {
    		panic(err)
    	}
    	fmt.Println("set : foo -> ", val)
    }
    
    func main() {
    	ExampleClient()
    }
  3. Execute o código.

PhpRedis

Este exemplo usa PHP 8.2.1 e PhpRedis 5.3.7.

  1. Baixe e instale o cliente PhpRedis.

  2. Conecte-se e execute comandos:

    <?php
    // Replace with your instance endpoint and port
    $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
    $port = 6379;
    // Replace with your account and password
    $user = "testaccount";
    $pwd = "Rp829dlwa";
    
    $redis = new Redis();
    if ($redis->connect($host, $port) == false) {
        die($redis->getLastError());
    }
    if ($redis->auth([$user, $pwd]) == false) {
        die($redis->getLastError());
    }
    if ($redis->set("foo", "bar") == false) {
        die($redis->getLastError());
    }
    $value = $redis->get("foo");
    echo $value;
    ?>
  3. Execute o script.

Erros comuns:
Cannot assign requested address : Consulte O erro "Cannot assign requested address" .
redis protocol error, got ' ' as reply type byte : Atualize seu cliente PhpRedis. Consulte phpredis/phpredis#1585 .

C ou C++

Este exemplo usa hiredis 1.1.0.

  1. Baixe e instale o hiredis.

  2. Escreva o seguinte código:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <hiredis.h>
    
    int main(int argc, char **argv) {
        unsigned int j;
        redisContext *c;
        redisReply *reply;
    
        if (argc < 4) {
            printf("Usage: example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 instance_id password\n");
            exit(0);
        }
    
        const char *hostname    = argv[1];
        const int   port        = atoi(argv[2]);
        const char *instance_id = argv[3];
        const char *password    = argv[4];
    
        struct timeval timeout = { 1, 500000 }; // 1.5 seconds
        c = redisConnectWithTimeout(hostname, port, timeout);
        if (c == NULL || c->err) {
            if (c) {
                printf("Connection error: %s\n", c->errstr);
                redisFree(c);
            } else {
                printf("Connection error: can't allocate redis context\n");
            }
            exit(1);
        }
    
        /* AUTH */
        reply = redisCommand(c, "AUTH %s", password);
        printf("AUTH: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* PING */
        reply = redisCommand(c, "PING");
        printf("PING: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* SET and GET */
        reply = redisCommand(c, "SET %s %s", "foo", "hello world");
        printf("SET: %s\n", reply->str);
        freeReplyObject(reply);
    
        reply = redisCommand(c, "SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
        printf("SET (binary API): %s\n", reply->str);
        freeReplyObject(reply);
    
        reply = redisCommand(c, "GET foo");
        printf("GET foo: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* INCR */
        reply = redisCommand(c, "INCR counter");
        printf("INCR counter: %lld\n", reply->integer);
        freeReplyObject(reply);
    
        reply = redisCommand(c, "INCR counter");
        printf("INCR counter: %lld\n", reply->integer);
        freeReplyObject(reply);
    
        /* List operations */
        reply = redisCommand(c, "DEL mylist");
        freeReplyObject(reply);
        for (j = 0; j < 10; j++) {
            char buf[64];
            snprintf(buf, 64, "%d", j);
            reply = redisCommand(c, "LPUSH mylist element-%s", buf);
            freeReplyObject(reply);
        }
        reply = redisCommand(c, "LRANGE mylist 0 -1");
        if (reply->type == REDIS_REPLY_ARRAY) {
            for (j = 0; j < reply->elements; j++) {
                printf("%u) %s\n", j, reply->element[j]->str);
            }
        }
        freeReplyObject(reply);
    
        /* Disconnect and free context */
        redisFree(c);
        return 0;
    }
  3. Compile:

    gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. Execute:

    ./example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 r-bp10noxlhcoim2**** password

.NET (StackExchange.Redis)

Este exemplo usa StackExchange.Redis 2.7.20.

Importante

Use a versão 2.7.20 ou posterior. Consulte Aviso sobre atualização do StackExchange.Redis.

  1. Baixe e instale o StackExchange.Redis.

  2. Configure um singleton ConnectionMultiplexer:

    ConfigurationOptions deve ser configurado como um singleton e compartilhado em toda a sua aplicação. Para todos os parâmetros disponíveis, consulte ConfigurationOptions . O objeto IDatabase retornado por GetDatabase() é leve — crie-o a cada uso a partir do ConnectionMultiplexer : `` csharp redisConn = GetRedisConn(); var db = redisConn.GetDatabase(); ``
    using StackExchange.Redis;
    
    // Set the endpoint, port, and password
    private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse(
        "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,password=testaccount:Rp829dlwa,connectTimeout=2000"
    );
    
    private static readonly object Locker = new object();
    private static ConnectionMultiplexer redisConn;
    
    public static ConnectionMultiplexer GetRedisConn()
    {
        if (redisConn == null)
        {
            lock (Locker)
            {
                if (redisConn == null || !redisConn.IsConnected)
                {
                    redisConn = ConnectionMultiplexer.Connect(configurationOptions);
                }
            }
        }
        return redisConn;
    }
  3. Execute comandos em tipos de dados comuns: String:

    String

    // SET and GETstring strKey = "hello";string strValue = "world";bool setResult = db.StringSet(strKey, strValue);Console.WriteLine("set " + strKey + " " + strValue + ", result is " + setResult);// INCRstring counterKey = "counter";long counterValue = db.StringIncrement(counterKey);Console.WriteLine("incr " + counterKey + ", result is " + counterValue);// EXPIREdb.KeyExpire(strKey, new TimeSpan(0, 0, 5));Thread.Sleep(5 * 1000);Console.WriteLine("expire " + strKey + ", after 5 seconds, value is " + db.StringGet(strKey));// MSET and MGETKeyValuePair<RedisKey, RedisValue> kv1 = new KeyValuePair<RedisKey, RedisValue>("key1", "value1");KeyValuePair<RedisKey, RedisValue> kv2 = new KeyValuePair<RedisKey, RedisValue>("key2", "value2");db.StringSet(new KeyValuePair<RedisKey, RedisValue>[] { kv1, kv2 });RedisValue[] values = db.StringGet(new RedisKey[] { kv1.Key, kv2.Key });Console.WriteLine("mget " + kv1.Key + " " + kv2.Key + ", result is " + values[0] + "&&" + values[1]);

    Hash

    string hashKey = "myhash";db.HashSet(hashKey, "f1", "v1");db.HashSet(hashKey, "f2", "v2");HashEntry[] values = db.HashGetAll(hashKey);Console.Write("hgetall " + hashKey + ", result is");for (int i = 0; i < values.Length; i++){    HashEntry hashEntry = values[i];    Console.Write(" " + hashEntry.Name + " " + hashEntry.Value);}Console.WriteLine();

    List

    string listKey = "myList";db.ListRightPush(listKey, "a");db.ListRightPush(listKey, "b");db.ListRightPush(listKey, "c");RedisValue[] values = db.ListRange(listKey, 0, -1);Console.Write("lrange " + listKey + " 0 -1, result is ");for (int i = 0; i < values.Length; i++){    Console.Write(values[i] + " ");}Console.WriteLine();

    Set

    string setKey = "mySet";db.SetAdd(setKey, "a");db.SetAdd(setKey, "b");db.SetAdd(setKey, "c");bool isContains = db.SetContains(setKey, "a");Console.WriteLine("set " + setKey + " contains a is " + isContains);

    Sorted Set

    string sortedSetKey = "myZset";db.SortedSetAdd(sortedSetKey, "xiaoming", 85);db.SortedSetAdd(sortedSetKey, "xiaohong", 100);db.SortedSetAdd(sortedSetKey, "xiaofei", 62);db.SortedSetAdd(sortedSetKey, "xiaotang", 73);RedisValue[] names = db.SortedSetRangeByRank(sortedSetKey, 0, 2, Order.Ascending);Console.Write("zrevrangebyscore " + sortedSetKey + " 0 2, result is ");for (int i = 0; i < names.Length; i++){    Console.Write(names[i] + " ");}Console.WriteLine();

Próximos passos