Tüm Ürünler
Search
Belge Merkezi

Tair (Redis® OSS-Compatible):İstemci kodu kullanarak bir örneğe bağlanma

Son Güncelleme:Oct 03, 2026

Tair (Redis OSS uyumlu) örnekleri, açık kaynaklı Redis ile tamamen uyumludur. Bir Redis veritabanına bağlandığınız gibi, Redis uyumlu herhangi bir istemci kullanarak bağlanabilirsiniz.

Ön koşullar

İstemcinizin çalıştığı konuma bağlı olarak aşağıdaki adımları tamamlayın.

İstemciniz bir ECS örneğinde çalışıyorsa (önerilir):

  1. Elastic Compute Service (ECS) örneğinin ve Tair örneğinin aynı sanal özel bulut (VPC) içinde olduğundan emin olun. VPC kimlikleri eşleşiyorsa örnekler aynı VPC içindedir.

    Not

    Örnekler farklı VPC'lerdeyse ECS örneğinin VPC'sini değiştirin. ECS örneği klasik ağda ve Tair örneği bir VPC'deyse bkz. Farklı ağ türlerinde olduklarında bir ECS örneğini bir Redis örneğine bağlama.

  2. ECS örneğinin dahili IP adresini alın.

  3. ECS örneğinin özel IP adresini izin listesine ekleyin.

İstemciniz yerel olarak çalışıyorsa:

  1. Makinenizin genel IP adresini alın:

    • Linux / macOS: Terminalde curl ifconfig.me komutunu çalıştırın.

    • Windows: Komut İstemi'nde curl ip.me komutunu çalıştırın.

  2. Genel IP adresini Tair örneğinin izin listesine ekleyin.

  3. Bir genel uç nokta için başvurun. Tair örnekleri varsayılan olarak yalnızca dahili uç noktalar sağlar.

Kullanım notları

  • Küme ve okuma/yazma ayırma mimarileri: Her ikisi de varsayılan olarak bir proxy düğüm uç noktası sağlar. Bu örneklere, standart mimariye sahip bir örneğe bağlandığınız gibi bağlanın.

    Doğrudan bağlantı uç noktası üzerinden bağlanırken açık kaynaklı Redis kümesine bağlanma yöntemini kullanın.
  • Parolasız erişim: VPC üzerinden parolasız erişim etkinleştirilirse aynı VPC'deki istemciler parola olmadan bağlanabilir.

Bağlantı bilgilerini alma

Kod yazmadan önce Örnekler sayfasından aşağıdaki bağlantı ayrıntılarını toplayın. Üst gezinme çubuğunda bölgenizi seçin, örnek kimliğine tıklayın ve Connection Information bölümüne gidin.


Ayrıntı


Nasıl alınır


Uç nokta


Uç noktaları ve bağlantı noktalarını Connection Information bölümünde görüntüleyin. Daha iyi güvenlik ve daha düşük gecikme süresi için VPC uç noktalarını kullanın. Bkz. Uç noktaları görüntüleme.


Bağlantı noktası


Varsayılan değer 6379 değeridir. Değiştirmek için bkz. Uç nokta veya bağlantı noktasını değiştirme.


Hesap


Varsayılan olarak her örneğin adı örnek kimliğiyle aynı olan bir hesabı vardır (örneğin r-bp10noxlhcoim2****). Ek hesaplar oluşturmak için bkz. Hesap oluşturma ve yönetme.


Parola


Biçim hesap türüne bağlıdır: varsayılan hesap — parolayı doğrudan girin; özel hesap — <username>:<password> biçimini kullanın (örneğin testaccount:Rp829dlwa).

Remote Desktop Manager (RDM) gibi üçüncü taraf araçları kullanırken parolayı username:password biçiminde girin. Unutulan bir parolayı sıfırlamak için bkz. Parolayı değiştirme veya sıfırlama .

İstemci seçme

Diliniz için istemciyi seçin. Sonraki bölümdeki tüm örnekler aynı Tair örneğine bağlanır.


Dil


İstemci


API stili


Notlar


Java


Jedis


Eşzamanlı


JedisPool aracılığıyla bağlantı havuzu


Java


Lettuce


Zaman uyumsuz ve reaktif


6.3.0.RELEASE veya sonraki sürümü kullanın


Java


Spring Data Redis


Eşzamanlı veya zaman uyumsuz


Hem Jedis hem de Lettuce arka uçlarını destekler


Python


redis-py


Eşzamanlı


Resmi Python istemcisi


Node.js


node-redis


Zaman uyumsuz


Resmi Node.js istemcisi


Go


go-redis


Eşzamanlı


Yaygın olarak kullanılan Go istemcisi


PHP


PhpRedis


Eşzamanlı


PHP için C uzantısı


C / C++


hiredis


Eşzamanlı


Minimalist C istemcisi


.NET


StackExchange.Redis


Eşzamanlı


2.7.20 veya sonraki sürümü kullanın

Desteklenen istemcilerin tam listesi için bkz. Redis Clients.

Önemli

ServiceStack Redis veya CSRedis istemcisini kullanmayın. ServiceStack Redis sorunları için doğrudan ServiceStack'ten destek satın almanız gerekir ve CSRedis desteği sona ermiştir.

Bağlanma ve test etme

Aşağıdaki örnekler, bağlanmak ve bir SET/GET komutu çalıştırmak için gereken minimum kodu gösterir. Tüm yer tutucu değerleri gerçek bağlantı ayrıntılarınızla değiştirin.

Jedis

Bu örnekte Jedis 4.3.0 kullanılmaktadır.

Bu örnekte Maven kullanılmaktadır. Jedis JAR dosyasını doğrudan da indirebilirsiniz.

  1. Bağımlılığı pom.xml dosyasına ekleyin:

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  2. Bağlanın ve komutları çalıştırın:

    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. Beklenen çıktı:

    bar
    [bike, car]
Önemli

Geçersiz parametrelerden veya özelliklerin yanlış kullanımından kaynaklanan Jedis hataları için bkz. Yaygın hatalar.

Lettuce

Bu örnekte Lettuce 6.3.0.RELEASE kullanılmaktadır.

Önemli

Lettuce 6.3.0.RELEASE veya sonraki sürümü kullanın ve TCP_USER_TIMEOUT parametresini ayarlayın. Bu, Lettuce istemcisindeki kara delik filtreleme sorunlarını önler.

Bu örnekte Maven kullanılmaktadır. Lettuce JAR dosyasını doğrudan da indirebilirsiniz.

  1. Aşağıdaki bağımlılıkları pom.xml dosyasına ekleyin:

    <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. Bağlanın ve komutları çalıştırın:

    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. Beklenen çıktı:

    OK
    bar

Spring Data Redis

Bu örnekte Spring Data Redis 2.4.2 kullanılmaktadır.

Önemli

Kara delik filtreleme sorunlarını önlemek için Lettuce sürüm 6.3.0.RELEASE veya üzerini kullanın ve TCP_USER_TIMEOUT değerini ayarlayın.

Bu örnekte, bağlantı arka ucu olarak Lettuce veya Jedis kullanan Maven kullanılmaktadır.

  1. Aşağıdakileri pom.xml dosyasına ekleyin:

    <?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. Bağlantı fabrikasını yapılandırın. Jedis veya Lettuce'i seçin: Jedis ile Spring Data Redis:

    @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);
    }

    Lettuce ile Spring Data Redis (TCP_USER_TIMEOUT dahil):

    @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. Kodu çalıştırın.

redis-py

Bu örnekte Python 3.9 ve redis-py 4.4.1 kullanılmaktadır.

  1. redis-py istemcisini indirin ve yükleyin.

  2. Bağlanın ve komutları çalıştırın:

    #!/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. Komut dosyasını çalıştırın.

node-redis

Bu örnekte Node.js 19.4.0 ve node-redis 4.5.1 kullanılmaktadır.

  1. node-redis'i indirin ve yükleyin.

  2. Bağlanın ve komutları çalıştırın:

    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. Komut dosyasını çalıştırın.

SyntaxError: Cannot use import statement outside a module hatasını görürseniz dosya adını .js uzantısından .mjs uzantısına değiştirin ve node --experimental-modules redis.mjs komutuyla çalıştırın.

go-redis

Bu örnekte Go 1.21 ve go-redis v9.18.0 kullanılmaktadır. Üretim ortamları için bağlantı havuzu ayarlarını (PoolSize, MinIdleConns) uygulamanızın eşzamanlılık gereksinimlerine ve Redis örneğinizin bağlantı sınırlarına uyacak şekilde ayarlamak çok önemlidir.

  1. go-redis istemcisini indirin ve yükleyin.

  2. Bağlanın ve komutları çalıştırın:

    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. Kodu çalıştırın.

PhpRedis

Bu örnekte PHP 8.2.1 ve PhpRedis 5.3.7 kullanılmaktadır.

  1. PhpRedis istemcisini indirin ve yükleyin.

  2. Bağlanın ve komutları çalıştırın:

    <?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. Komut dosyasını çalıştırın.

Yaygın hatalar:
Cannot assign requested address : Bkz. "Cannot assign requested address" hatası .
redis protocol error, got ' ' as reply type byte : PhpRedis istemcinizi yükseltin. Bkz. phpredis/phpredis#1585 .

C veya C++

Bu örnekte hiredis 1.1.0 kullanılmaktadır.

  1. hiredis'i indirin ve yükleyin.

  2. Aşağıdaki kodu yazın:

    #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. Derleyin:

    gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. Çalıştırın:

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

.NET (StackExchange.Redis)

Bu örnekte StackExchange.Redis 2.7.20 kullanılmaktadır.

Önemli

2.7.20 veya sonraki sürümü kullanın. Bkz. StackExchange.Redis güncellemesi hakkında bildirim.

  1. StackExchange.Redis'i indirin ve yükleyin.

  2. Tekil bir ConnectionMultiplexer ayarlayın:

    ConfigurationOptions tekil olarak yapılandırılmalı ve uygulamanız genelinde paylaşılmalıdır. Kullanılabilir tüm parametreler için bkz. ConfigurationOptions . IDatabase nesnesi GetDatabase() tarafından döndürülür ve hafiftir; her kullanımda ConnectionMultiplexer üzerinden oluşturun: `` 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. Yaygın veri türlerinde komutları çalıştırın: 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();

Sonraki adımlar