すべてのプロダクト
Search
ドキュメントセンター

Tair (Redis® OSS-Compatible):クライアントコードによるインスタンスへの接続

最終更新日:Jul 10, 2026

Tair (Redis OSS-compatible) インスタンスは、オープンソースの Redis と完全な互換性があります。Redis データベースへの接続と同様に、Redis 互換のクライアントを使用して接続できます。

前提条件

クライアントが実行される場所に応じて、以下の手順を実行してください。

クライアントを ECS インスタンス上で実行する場合 (推奨):

  1. Elastic Compute Service (ECS) インスタンスと Tair インスタンスが同じ Virtual Private Cloud (VPC) 内にあることを確認してください。VPC ID が一致する場合、インスタンスは同じ VPC 内にあります。

    説明

    インスタンスが異なる VPC にある場合は、ECS インスタンスの VPC を変更してください。ECS インスタンスがクラシックネットワークにあり、Tair インスタンスが VPC にある場合は、「異なるネットワークタイプにある ECS インスタンスを Redis インスタンスに接続する」をご参照ください。

  2. ECS インスタンスの内部 IP アドレスを取得してください

  3. ECS インスタンスのプライベート IP アドレスをホワイトリストに追加してください

クライアントをローカルで実行する場合:

  1. お使いのマシンのパブリック IP アドレスを取得してください:

    • Linux / macOS:ターミナルで curl ifconfig.me を実行します。

    • Windows:コマンドプロンプトで curl ip.me を実行します。

  2. パブリック IP アドレスを Tair インスタンスのホワイトリストに追加してください

  3. パブリックエンドポイントを申請してください。Tair インスタンスはデフォルトで内部エンドポイントのみを提供します。

注意事項

  • クラスターアーキテクチャと読み書き分離アーキテクチャ:どちらもデフォルトでプロキシノードのエンドポイントを提供します。これらのインスタンスへの接続は、標準アーキテクチャのインスタンスへの接続と同じ方法で行います。

    直接接続エンドポイント経由で接続する場合、オープンソースの Redis クラスターへの接続と同じ方法を使用してください。
  • パスワード不要のアクセスVPC 経由のパスワード不要のアクセスが有効になっている場合、同じ VPC 内のクライアントはパスワードなしで接続できます。

接続情報の取得

コードを記述する前に、インスタンスページから以下の接続詳細を収集してください。上部メニューでリージョンを選択し、インスタンス ID をクリックして、[Connection Information] セクションに移動してください。

詳細

取得方法

エンドポイント

[Connection Information] セクションでエンドポイントとポートを表示できます。セキュリティの向上とレイテンシーの低減のために VPC エンドポイントを使用してください。詳細については、「エンドポイントの表示」をご参照ください。

ポート

デフォルトは 6379 です。変更するには、「エンドポイントまたはポートの変更」をご参照ください。

アカウント

デフォルトでは、各インスタンスにはインスタンス ID にちなんで名付けられたアカウントがあります (例:r-bp10noxlhcoim2****)。追加のアカウントを作成するには、「アカウントの作成と管理」をご参照ください。

パスワード

形式はアカウントタイプによって異なります:デフォルトアカウント — パスワードを直接入力してください。カスタムアカウント — <username>:<password> の形式を使用してください (例:testaccount:Rp829dlwa)。

Remote Desktop Manager (RDM) などのサードパーティツールを使用する場合、パスワードは username:password 形式で入力してください。忘れたパスワードをリセットするには、「パスワードの変更またはリセット」をご参照ください。

クライアントの選択

お使いの言語のクライアントを選択してください。次のセクションのすべての例は、同じ Tair インスタンスに接続します。

言語

クライアント

API スタイル

注意

Java

Jedis

同期

JedisPool によるコネクションプーリング

Java

Lettuce

非同期およびリアクティブ

バージョン 6.3.0.RELEASE 以降を使用してください

Java

Spring Data Redis

同期または非同期

Jedis と Lettuce の両方のバックエンドをサポート

Python

redis-py

同期

公式 Python クライアント

Node.js

node-redis

非同期

公式 Node.js クライアント

Go

go-redis

同期

広く使用されている Go クライアント

PHP

PhpRedis

同期

PHP の C 拡張

C / C++

hiredis

同期

最小限の C クライアント

.NET

StackExchange.Redis

同期

バージョン 2.7.20 以降を使用してください

対応クライアントの完全なリストについては、「Redis Clients」をご参照ください。

重要

ServiceStack Redis または CSRedis クライアントは使用しないでください。ServiceStack Redis の問題については、ServiceStack から直接サポートを購入する必要があります。また、CSRedis のサポートは終了しています。

接続とテスト

以下の例は、接続して SET/GET コマンドを実行するために必要な最小限のコードを示しています。すべてのプレースホルダー値を実際の接続詳細に置き換えてください。

Jedis

この例では Jedis 4.3.0 を使用します。

この例では Maven を使用します。Jedis JAR を直接ダウンロードすることもできます。

  1. pom.xml に依存関係を追加してください:

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  2. 接続してコマンドを実行してください:

    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();
            // 最大アイドル接続数 — インスタンスの接続数制限を超えないようにする必要があります
            config.setMaxIdle(200);
            // 最大合計接続数 — インスタンスの接続数制限を超えないようにする必要があります
            config.setMaxTotal(300);
            config.setTestOnBorrow(false);
            config.setTestOnReturn(false);
    
            // お使いのインスタンスのエンドポイントとパスワードに置き換えてください
            String host = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com";
            // デフォルトアカウント:パスワードを直接入力してください
            // カスタムアカウント:「username:password」形式を使用してください
            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();
                }
            }
            // アプリケーションのシャットダウン時にこれを呼び出してリソースを解放してください
            pool.destroy();
        }
    }
  3. 期待される出力:

    bar
    [bike, car]
重要

無効なパラメーターまたは不適切な機能の使用によって引き起こされる Jedis のエラーについては、「一般的なエラー」をご参照ください。

Lettuce

この例では Lettuce 6.3.0.RELEASE を使用します。

重要

Lettuce 6.3.0.RELEASE 以降を使用し、TCP_USER_TIMEOUT パラメーターを設定してください。これにより、Lettuce クライアントでのブラックホールフィルタリングの問題を防ぎます。

この例では Maven を使用します。Lettuce JAR を直接ダウンロードすることもできます。

  1. 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. 接続してコマンドを実行してください:

    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 {
        /**
         * 次の設定で TCP keepalive を有効にします:
         *   TCP_KEEPIDLE  = 30 秒
         *   TCP_KEEPINTVL = 10 秒
         *   TCP_KEEPCNT   = 3
         */
        private static final int TCP_KEEPALIVE_IDLE = 30;
    
        /**
         * TCP_USER_TIMEOUT は、障害またはクラッシュ中に Lettuce がタイムアウトループでスタックするのを防ぎます。
         * 参照: 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) {
            // お使いのインスタンス情報に置き換えてください
            String host     = "r-bp1s1bt2tlq3p1****.redis.rds.aliyuncs.com";
            String user     = "r-bp1s1bt2tlq3p1****";
            String password = "Da****3";
            int    port     = 6379;
    
            // RedisURI をビルドします
            RedisURI uri = RedisURI.Builder
                    .redis(host, port)
                    .withAuthentication(user, password)
                    .build();
    
            // TCP keepalive と 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"));
    
            // シャットダウン — 接続を閉じてリソースを解放します
            connection.close();
            client.shutdown();
        }
    }
  3. 期待される出力:

    OK
    bar

Spring Data Redis

この例では Spring Data Redis 2.4.2 を使用します。

重要

Lettuce バージョン 6.3.0.RELEASE 以降を使用し、ブラックホールフィルタリングの問題を防ぐために TCP_USER_TIMEOUT を設定してください。

この例では、接続バックエンドとして Lettuce または Jedis を使用する Maven を使用します。

  1. 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. 接続ファクトリを設定してください。Jedis または Lettuce を選択します:Jedis を使用した Spring Data Redis:

    @Bean
    JedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", port);
    
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大合計接続数 — インスタンスの接続数制限を超えないようにする必要があります
        jedisPoolConfig.setMaxTotal(30);
        // 最大アイドル接続数 — インスタンスの接続数制限を超えないようにする必要があります
        jedisPoolConfig.setMaxIdle(20);
        // 追加の PING コマンドを避けるために testOn[Borrow|Return] を無効にします
        jedisPoolConfig.setTestOnBorrow(false);
        jedisPoolConfig.setTestOnReturn(false);
    
        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder()
            .usePooling()
            .poolConfig(jedisPoolConfig)
            .build();
    
        return new JedisConnectionFactory(config, jedisClientConfiguration);
    }

    Lettuce を使用した Spring Data Redis (TCP_USER_TIMEOUT を含む):

    @Configuration
    public class BeanConfig {
        /**
         * 次の設定で TCP keepalive を有効にします:
         *   TCP_KEEPIDLE  = 30 秒
         *   TCP_KEEPINTVL = 10 秒
         *   TCP_KEEPCNT   = 3
         */
        private static final int TCP_KEEPALIVE_IDLE = 30;
    
        /**
         * TCP_USER_TIMEOUT は、障害またはクラッシュ中に Lettuce がタイムアウトループでスタックするのを防ぎます。
         * 参照: 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. コードを実行してください。

redis-py

この例では Python 3.9 と redis-py 4.4.1 を使用します。

  1. redis-py クライアントをダウンロードしてインストールします

  2. 接続してコマンドを実行してください:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import redis
    
    # お使いのインスタンスのエンドポイントとポートに置き換えてください
    host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    # デフォルトアカウント:パスワードを直接入力してください
    # カスタムアカウント:「username:password」形式を使用してください
    pwd = 'testaccount:Rp829dlwa'
    
    r = redis.Redis(host=host, port=port, password=pwd)
    r.set('foo', 'bar')
    print(r.get('foo'))
  3. スクリプトを実行してください。

node-redis

この例では Node.js 19.4.0 と node-redis 4.5.1 を使用します。

  1. node-redis をダウンロードしてインストールします

  2. 接続してコマンドを実行してください:

    import { createClient } from 'redis';
    
    // お使いのインスタンスのエンドポイント、ポート、アカウント、パスワードに置き換えてください
    const host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com';
    const port = 6379;
    const username = 'testaccount';
    // パスワードに特殊文字 (!@#$%^&*()+-=_) が含まれている場合は、まずエンコードします:
    // 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. スクリプトを実行してください。

SyntaxError: Cannot use import statement outside a module が表示された場合は、ファイル名を .js から .mjs に変更し、node --experimental-modules redis.mjs で実行してください。

go-redis

この例では Go 1.21 と go-redis v9.18.0 を使用します。 本番環境では、アプリケーションの同時実行要求と Redis インスタンスの接続制限に合わせて、接続プールの設定 (PoolSize、MinIdleConns) を調整することが重要です

  1. go-redis クライアントをダウンロードしてインストールします

  2. 接続してコマンドを実行してください:

    package main
    
    import (
    	"context"
    	"fmt"
    	"time"
    
    	"github.com/redis/go-redis/v9"
    )
    
    var ctx = context.Background()
    
    func ExampleClient() {
    	client := redis.NewClient(&redis.Options{
    		// お使いのインスタンスのエンドポイントとポートに置き換えてください。
    		Addr: "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
    		// お使いのインスタンスのパスワードに置き換えてください。
    		Password: "testaccount:Rp829dlwa",
    		DB:       0, // デフォルトの DB を使用します。
    
    		// 接続プールの設定。ワークロードに合わせてこれらを調整し、インスタンスの最大接続数制限を超えないようにしてください。
    		PoolSize:     20,              // 最大接続数。推奨値:ピーク QPS / 1接続あたりの QPS、または CPU コア数の約 10 倍。
    		MinIdleConns: 5,               // 最小アイドル接続数。新規接続を確立することなくトラフィックの急増に対応するために、プールを事前にウォームアップします。
    		PoolTimeout:  4 * time.Second, // プールから接続を取得する際の待機時間。ReadTimeout より少し大きく設定します。
    		ConnMaxIdleTime:  5 * time.Minute, // アイドル状態の接続を閉じるまでの時間。インスタンスのアイドルタイムアウト (デフォルト 600 秒) 未満に設定する必要があります。
    
    		// ネットワークとリトライの設定。
    		DialTimeout:  5 * time.Second, // TCP 接続を確立するためのタイムアウト。
    		ReadTimeout:  3 * time.Second, // 読み取りタイムアウト。-1 はタイムアウトを無効にし、0 はデフォルトを使用します。
    		WriteTimeout: 3 * time.Second, // 書き込みタイムアウト。
    		MaxRetries:   3,               // 失敗時のコマンドリトライ回数。-1 はリトライを無効にします。
    	})
    	defer client.Close()
    
    	// 以下のコードは SET/GET の例を示しています。
    	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. コードを実行してください。

PhpRedis

この例では PHP 8.2.1 と PhpRedis 5.3.7 を使用します。

  1. PhpRedis クライアントをダウンロードしてインストールします

  2. 接続してコマンドを実行してください:

    <?php
    // お使いのインスタンスのエンドポイントとポートに置き換えてください
    $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
    $port = 6379;
    // お使いのアカウントとパスワードに置き換えてください
    $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. スクリプトを実行してください。

一般的なエラー:
Cannot assign requested address: 「"Cannot assign requested address" エラー」をご参照ください。
redis protocol error, got ' ' as reply type byte: PhpRedis クライアントをアップグレードしてください。 「phpredis/phpredis#1585」をご参照ください。

C または C++

この例では hiredis 1.1.0 を使用します。

  1. hiredis をダウンロードしてインストールします

  2. 次のコードを記述してください:

    #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 秒
        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 と 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);
    
        /* リスト操作 */
        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);
    
        /* 切断とコンテキストの解放 */
        redisFree(c);
        return 0;
    }
  3. コンパイル:

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

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

.NET (StackExchange.Redis)

この例では StackExchange.Redis 2.7.20 を使用します。

重要

バージョン 2.7.20 以降を使用してください。詳細については、「StackExchange.Redis の更新に関する通知」をご参照ください。

  1. StackExchange.Redis をダウンロードしてインストールします

  2. シングルトンの ConnectionMultiplexer を設定してください:

    ConfigurationOptions はシングルトンとして設定し、アプリケーション全体で共有する必要があります。利用可能なすべてのパラメーターについては、「ConfigurationOptions」をご参照ください。GetDatabase() によって返される IDatabase オブジェクトは軽量です。使用するたびに ConnectionMultiplexer から作成してください: var db = redisConn.GetDatabase();
    using StackExchange.Redis;
    
    // エンドポイント、ポート、パスワードを設定してください
    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. 一般的なデータ型でコマンドを実行してください:String:

    String

    // SET と GET
    string strKey = "hello";
    string strValue = "world";
    bool setResult = db.StringSet(strKey, strValue);
    Console.WriteLine("set " + strKey + " " + strValue + ", result is " + setResult);
    // INCR
    string counterKey = "counter";
    long counterValue = db.StringIncrement(counterKey);
    Console.WriteLine("incr " + counterKey + ", result is " + counterValue);
    // EXPIRE
    db.KeyExpire(strKey, new TimeSpan(0, 0, 5));
    Thread.Sleep(5 * 1000);
    Console.WriteLine("expire " + strKey + ", after 5 seconds, value is " + db.StringGet(strKey));
    // MSET と MGET
    KeyValuePair<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);

    ソート済みセット

    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("zrange " + sortedSetKey + " 0 2, result is ");
    for (int i = 0; i < names.Length; i++)
    {
        Console.Write(names[i] + " ");
    }
    Console.WriteLine();

次のステップ