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

PolarDB:Orca 接続ガイド

最終更新日:Dec 19, 2025

PolarDB for MySQL の Orca 機能は Redis プロトコルと互換性があります。この互換性により、主要な Redis クライアントを使用してデータベースに接続できます。このトピックでは、接続の前提条件について説明し、いくつかの一般的なプログラミング言語のクライアント向けのコード例を紹介します。

事前準備

Orca 機能に接続する前に、次の前提条件を満たしてください。

注意事項

  • 認証メカニズムの違い:Orca 機能の認証メカニズムは、ネイティブの Redis とは異なります。Orca にはデフォルトユーザーが存在しません。すべての接続は、コンソールで作成した Orca アカウントを使用して認証する必要があります。

  • AUTH コマンドの互換性:パスワード認証のみをサポートする一部のクライアントとの互換性を確保するため、Orca の AUTH コマンドは 2 つのフォーマットをサポートしています。クライアントを設定する際は、クライアントの機能に応じて適切な認証方式を選択してください。

    • AUTH <username> <password>:標準フォーマットです。ユーザー名とパスワードを別々に指定します。

    • AUTH <username>:<password>:互換性フォーマットです。ユーザー名とパスワードをコロン (:) で連結し、文字列全体をパスワードパラメーターとして渡します。

  • HELLO コマンドの互換性AUTH コマンドと同様に、HELLO コマンドの認証部分も上記の 2 つのフォーマットをサポートしています。

    • HELLO <protover> AUTH <username> <password>

    • HELLO <protover> AUTH <username>:<password>

redis-cli を使用した接続

  1. redis-cli のインストール:ご利用のクライアントデバイスに redis-cli をインストールします。詳細については、「redis-cli インストールチュートリアル」をご参照ください。

  2. Orca 機能への接続:次のコマンドを実行します。エンドポイントとポートを実際の値に置き換えてください。

    redis-cli -h pz-****************.rwlb.rds.aliyuncs.com -p 6379
  3. 接続の認証:接続に成功したら、AUTH コマンドを使用して認証します。以下の両方のフォーマットがサポートされています。プレースホルダーをご利用の Orca ユーザー名とパスワードに置き換えてください。

    # フォーマット 1:ユーザー名とパスワードを別々に指定
    AUTH orca_user orca_password
    
    # フォーマット 2:ユーザー名とパスワードを連結してパスワードとして指定
    AUTH orca_user:orca_password

    OK が返された場合、接続と認証は成功です。

各種言語のクライアントを使用した接続

ご利用のアプリケーションのプログラミング言語に応じて、以下の例を参照して接続してください。

Java (Jedis)

  1. 依存関係の設定を追加します (Maven):

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>4.3.0</version>
    </dependency>
  2. コード例:Jedis はパスワードパラメーターを 1 つしか受け付けないため、互換性のために username:password フォーマットを使用します。

    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 poolConfig = new JedisPoolConfig();
            
            // Orca 接続情報
            String host = "pz-****************.rwlb.rds.aliyuncs.com"; // ご利用の Orca エンドポイントに置き換えてください
            int port = 6379;
            String username = "orca_user"; // ご利用の Orca ユーザー名に置き換えてください
            String password = "orca_password"; // ご利用の Orca パスワードに置き換えてください
    
            // Jedis の認証では、ユーザー名とパスワードを連結する必要があります
            String authPassword = username + ":" + password;
    
            JedisPool pool = new JedisPool(poolConfig, host, port, 3000, authPassword);
            
            try (Jedis jedis = pool.getResource()) {
                jedis.set("name", "jedis");
                System.out.println(jedis.get("name"));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                pool.destroy();
            }
        }
    }
    

Java (Lettuce)

  1. 依存関係の設定を追加します (Maven):

    <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>
  2. コード例:Lettuce はユーザー名とパスワードを個別に設定することをサポートしています。このメソッドを推奨します。

    import io.lettuce.core.RedisClient;
    import io.lettuce.core.RedisURI;
    import io.lettuce.core.api.StatefulRedisConnection;
    import io.lettuce.core.api.sync.RedisCommands;
    
    public class LettuceExample {
        public static void main(String[] args) {
            // Orca 接続情報
            String host = "pz-****************.rwlb.rds.aliyuncs.com"; // ご利用の Orca エンドポイントに置き換えてください
            int port = 6379;
            String username = "orca_user"; // ご利用の Orca ユーザー名に置き換えてください
            String password = "orca_password"; // ご利用の Orca パスワードに置き換えてください
    
            // Lettuce はユーザー名とパスワードの個別設定をサポートしています
            RedisURI uri = RedisURI.Builder
                    .redis(host, port)
                    .withAuthentication(username, password)
                    .build();
            RedisClient redisClient = RedisClient.create(uri);
    
            StatefulRedisConnection<String, String> connection = redisClient.connect();
    
            RedisCommands<String, String> syncCommands = connection.sync();
    
            syncCommands.set("name", "Lettuce");
            String value = syncCommands.get("name");
            // 出力:Lettuce
            System.out.println("Get value: " + value); 
    
            connection.close();
            redisClient.shutdown();
        }
    }

Java (Spring Data Redis)

  1. 依存関係の設定を追加します (Maven):

    <!-- バージョン管理を統一するための Spring Boot 親プロジェクト -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version> <!-- 最近の安定バージョンを推奨します -->
        <relativePath/>
    </parent>
    
    <!-- その他の設定項目... -->
    
    <dependencies>
        <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>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.36</version>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <!-- パッケージングと実行のための Spring Boot Maven プラグイン -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  2. コード例:以下のいずれかの方法を選択して設定を行い、Orca に接続します。

    application.yml による設定

    Spring Boot 2.x 以降では、application.yml でユーザー名とパスワードを個別に指定できます。この方法を推奨します。

    1. プロジェクトのファイル構造は次のとおりです。

      test_redis/
      ├── pom.xml
      └── src/
          └── main/
              ├── java/
              │   └── com/
              │       └── example/
              │           ├── MainApplication.java
              │           └── RedisTestRunner.java
              └── resources/
                  └── application.yml
      
    2. application.yml の設定:src/main/resources/ ディレクトリに application.yml ファイルを作成します。このファイルにはすべての設定情報が格納されます。

      spring:
        redis:
          host: pz-****************.rwlb.rds.aliyuncs.com # ご利用の Orca エンドポイントに置き換えてください
          port: 6379
          username: orca_user      # ご利用の Orca ユーザー名に置き換えてください
          password: orca_password  # ご利用の Orca パスワードに置き換えてください
          database: 0
          jedis:
            pool:
              max-active: 30
              max-idle: 20
              min-idle: 5
              max-wait: -1ms
    3. メインの起動クラス MainApplication.java の作成:これは Spring Boot アプリケーションのエントリポイントです。

      package com.example;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      
      @SpringBootApplication
      public class MainApplication {
          public static void main(String[] args) {
              SpringApplication.run(MainApplication.class, args);
          }
      }
    4. テストクラス RedisTestRunner.java の作成:このクラスは Spring Boot アプリケーションの起動後に自動的に実行されます。Redis の読み書き操作を行い、結果を出力します。

      package com.example;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.CommandLineRunner;
      import org.springframework.data.redis.core.StringRedisTemplate;
      import org.springframework.stereotype.Component;
      
      @Component
      public class RedisTestRunner implements CommandLineRunner {
      
          @Autowired
          private StringRedisTemplate stringRedisTemplate;
      
          @Override
          public void run(String... args) throws Exception {
              System.out.println("=== Starting Redis test with Spring Data Redis ===");
      
              try {
                  // キーと値のペアを定義
                  String key = "name";
                  String value = "spring-data-redis";
      
                  // 1. SET コマンドの実行
                  stringRedisTemplate.opsForValue().set(key, value);
                  System.out.println("SET " + key + " = " + value);
      
                  // 2. GET コマンドの実行
                  String retrievedValue = stringRedisTemplate.opsForValue().get(key);
                  System.out.println("GET " + key + " = " + retrievedValue);
      
                  // 3. 結果の検証
                  if (value.equals(retrievedValue)) {
                      System.out.println("Test successful!");
                  } else {
                      System.out.println("Test failed! Retrieved value does not match.");
                  }
      
              } catch (Exception e) {
                  System.err.println("Redis operation failed: " + e.getMessage());
                  e.printStackTrace();
              }
      
              System.out.println("=== Redis test completed ===");
          }
      }

    Java Config を使用した設定

    古いバージョンの Spring を使用している場合や、カスタム要件がある場合は、Java 設定クラスを使用できます。下位レイヤーで Jedis が使用されるため、認証には引き続きユーザー名とパスワードを連結する必要があります。

    1. プロジェクトのファイル構造は次のとおりです。

      test_redis/
      ├── pom.xml
      └── src/
          └── main/
              ├── java/
              │   └── com/
              │       └── example/
              │           ├── config/
              │           │   └── RedisConfig.java   <-- コア設定クラス
              │           ├── MainApplication.java
              │           └── RedisTestRunner.java
              └── resources/
                  └── application.yml            <-- このファイルは削除するか、空のままにすることができます
    2. コア設定クラス RedisConfig.java の作成:このクラスでは、RedisConnectionFactory の Bean を手動で作成し、すべての接続詳細を指定できます。Spring Boot はこの Bean を自動的に検出し、StringRedisTemplate などのすべての Redis 関連操作を設定するために使用します。

      package com.example.config;
      
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.data.redis.connection.RedisConnectionFactory;
      import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
      import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
      
      @Configuration
      public class RedisConfig {
      
          @Bean
          public RedisConnectionFactory redisConnectionFactory() {
              // 1. スタンドアロン Redis 設定を作成
              RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
      
              // 2. Orca 接続情報を設定
              // ご利用の Orca エンドポイントに置き換えてください
              redisConfig.setHostName("pz-****************.rwlb.rds.aliyuncs.com"); 
              // Orca ポート、デフォルトは 6379
              redisConfig.setPort(6379);
              // ご利用の Orca ユーザー名に置き換えてください
              redisConfig.setUsername("orca_user");
              // ご利用の Orca パスワードに置き換えてください
              redisConfig.setPassword("orca_password");
              
              // 3. クライアントとして Lettuce を使用し、上記の設定を適用
              LettuceConnectionFactory lettuceFactory = new LettuceConnectionFactory(redisConfig);
              
              // オプション:afterPropertiesSet を呼び出さない場合、Spring コンテナーは Bean の初期化時に自動的に呼び出します。
              // lettuceFactory.afterPropertiesSet();
      
              // 4. 設定済みの接続ファクトリインスタンスを返す
              return lettuceFactory;
          }
      }
      
    3. メインの起動クラス MainApplication.java の作成:これは Spring Boot アプリケーションのエントリポイントです。

      package com.example;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      
      @SpringBootApplication
      public class MainApplication {
          public static void main(String[] args) {
              SpringApplication.run(MainApplication.class, args);
          }
      }
    4. テストクラス RedisTestRunner.java の作成:このクラスは Spring Boot アプリケーションの起動後に自動的に実行されます。Redis の読み書き操作を行い、結果を出力します。

    5. package com.example;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.CommandLineRunner;
      import org.springframework.data.redis.core.StringRedisTemplate;
      import org.springframework.stereotype.Component;
      
      @Component
      public class RedisTestRunner implements CommandLineRunner {
      
          @Autowired
          private StringRedisTemplate stringRedisTemplate;
      
          @Override
          public void run(String... args) throws Exception {
              System.out.println("=== Starting Redis test with Spring Data Redis ===");
      
              try {
                  // キーと値のペアを定義
                  String key = "name";
                  String value = "spring-data-redis";
      
                  // 1. SET コマンドの実行
                  stringRedisTemplate.opsForValue().set(key, value);
                  System.out.println("SET " + key + " = " + value);
      
                  // 2. GET コマンドの実行
                  String retrievedValue = stringRedisTemplate.opsForValue().get(key);
                  System.out.println("GET " + key + " = " + retrievedValue);
      
                  // 3. 結果の検証
                  if (value.equals(retrievedValue)) {
                      System.out.println("Test successful!");
                  } else {
                      System.out.println("Test failed! Retrieved value does not match.");
                  }
      
              } catch (Exception e) {
                  System.err.println("Redis operation failed: " + e.getMessage());
                  e.printStackTrace();
              }
      
              System.out.println("=== Redis test completed ===");
          }
      }

Python (redis-py)

  1. 依存関係をインストールします。

    pip install redis
  2. コード例:redis-py バージョン 4.2 以降は、個別の username パラメーターをサポートしています。古いバージョンを使用する場合は、password パラメーターに username:password フォーマットを使用してください。

    import redis
    
    # Orca 接続情報
    host = 'pz-****************.rwlb.rds.aliyuncs.com'  # ご利用の Orca エンドポイントに置き換えてください
    port = 6379
    username = 'orca_user'  # ご利用の Orca ユーザー名に置き換えてください
    password = 'orca_password'  # ご利用の Orca パスワードに置き換えてください
    
    # 推奨される方法 (redis-py >= 4.2)
    r = redis.Redis(host=host, port=port, username=username, password=password)
    
    # 古いバージョンとの互換性のための方法
    # auth_password = f'{username}:{password}'
    # r = redis.Redis(host=host, port=port, password=auth_password)
    
    r.set('name', 'redis-py')
    print(r.get('name').decode('utf-8'))
    r.close()
    

Go (go-redis)

  1. 依存関係をインストールします。

    go get github.com/go-redis/redis/v8
  2. コード例:go-redis は個別の Username フィールドをサポートしています。このメソッドを推奨します。古いクライアントバージョンを使用する場合は、Password フィールドの値として username:password を使用してください。

    package main
    
    import (
        "context"
        "fmt"
        "github.com/go-redis/redis/v8"
    )
    
    var ctx = context.Background()
    
    func main() {
        client := redis.NewClient(&redis.Options{
            Addr:     "pz-****************.rwlb.rds.aliyuncs.com:6379", // ご利用の Orca アドレスとポートに置き換えてください
            Username: "orca_user",     // ご利用の Orca ユーザー名に置き換えてください
            Password: "orca_password", // ご利用の Orca パスワードに置き換えてください
            DB:       0,
        })
    
        err := client.Set(ctx, "name", "go-redis", 0).Err()
        if err != nil {
            panic(err)
        }
    
        val, err := client.Get(ctx, "name").Result()
        if err != nil {
            panic(err)
        }
        fmt.Println("Get value:", val)
    }
    

Node.js (node-redis)

  1. 依存関係をインストールします。

    npm install redis
  2. コード例:node-redis は、接続 URL に認証情報を含めることをサポートしています。

    import { createClient } from 'redis';
    
    // Orca 接続情報
    const host = 'pz-****************.rwlb.rds.aliyuncs.com'; // ご利用の Orca エンドポイントに置き換えてください
    const port = 6379;
    const username = 'orca_user'; // ご利用の Orca ユーザー名に置き換えてください
    const password = 'orca_password'; // ご利用の Orca パスワードに置き換えてください
    
    const client = createClient({
        url: `redis://${username}:${encodeURIComponent(password)}@${host}:${port}/0`
    });
    
    client.on('error', (err) => console.error('Redis Client Error:', err));
    
    async function runExample() {
        try {
            await client.connect();
            await client.set('name', 'node-redis');
            const value = await client.get('name');
            console.log('get name:', value);
        } finally {
            await client.disconnect();
        }
    }
    
    runExample();
    

PHP (PhpRedis)

  1. 依存関係をインストールします:通常、パッケージマネージャーを使用してインストールできます。例えば、CentOS の場合:

    sudo yum install php-redis
  2. コード例:PhpRedis 拡張機能の auth メソッドは、ユーザー名とパスワードを含む配列を渡すことをサポートしています。

    <?php
    $redis = new Redis();
    
    // Orca 接続情報
    $host = 'pz-****************.rwlb.rds.aliyuncs.com'; // ご利用の Orca エンドポイントに置き換えてください
    $port = 6379;
    $user = 'orca_user';     // ご利用の Orca ユーザー名に置き換えてください
    $password = 'orca_password'; // ご利用の Orca パスワードに置き換えてください
    
    if ($redis->connect($host, $port) === false) {
        die($redis->getLastError());
    }
    
    // ユーザー名とパスワードを含む配列を使用して認証
    if ($redis->auth([$user, $password]) === false) {
        die($redis->getLastError());
    }
    
    $redis->set("name", "php-redis");
    echo $redis->get("name");
    
    $redis->close();
    ?>
    

C (Hiredis)

  1. 依存関係のインストール:ソースコードからコンパイルしてインストールします。

    git clone https://github.com/redis/hiredis.git
    cd hiredis
    make && sudo make install
  2. コード例:redisCommand を使用して AUTH コマンドを実行します。連結された username:password フォーマットを使用できます。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <hiredis.h>
    
    int main() {
        // Orca 接続パラメーター
        const char *hostname = "********.rwlb.rds.aliyuncs.com"; // ご利用の Orca エンドポイントに置き換えてください
        int port = 6379;
        // 使いやすさのためにユーザー名とパスワードを別々に定義
        const char *username = "orca_user"; // ご利用の Orca ユーザー名に置き換えてください
        const char *password = "orca_password"; // ご利用の Orca パスワードに置き換えてください
    
        redisContext *c;
        redisReply *reply;
    
        // 1. Redis に接続 (タイムアウト付きの接続を推奨)
        struct timeval timeout = { 2, 0 }; // 2 秒のタイムアウト
        c = redisConnectWithTimeout(hostname, port, timeout);
        if (c == NULL || c->err) {
            if (c) {
                printf("Connection error: %s\n", c->errstr);
                redisFree(c);
            } else {
                printf("Can't allocate redis context\n");
            }
            exit(1);
        }
    
        // 2. 認証
        // "AUTH <username> <password>" フォーマットを使用
        reply = redisCommand(c, "AUTH %s %s", username, password);
        if (reply == NULL) {
            // reply が NULL の場合、I/O エラーが発生。c->errstr を確認
            printf("AUTH command failed: %s\n", c->errstr);
            redisFree(c);
            exit(1);
        }
        // 応答自体がエラータイプかどうかを確認
        if (reply->type == REDIS_REPLY_ERROR) {
            printf("Authentication failed: %s\n", reply->str);
            freeReplyObject(reply);
            redisFree(c);
            exit(1);
        }
        printf("Authenticated successfully\n");
        freeReplyObject(reply); // 認証成功後、応答を解放することを忘れないでください
    
        // 3. SET コマンドを実行
        reply = redisCommand(c, "SET mykey %s", "Hello, hiredis!");
        if (reply == NULL) {
            printf("SET command failed: %s\n", c->errstr);
            redisFree(c);
            exit(1);
        }
    
        // 成功した SET コマンドに対して、hiredis は STATUS タイプの応答を返します
        if (reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "OK") == 0) {
            printf("SET mykey succeeded\n");
        } else {
            printf("SET failed with reply: %s\n", reply->str);
        }
        freeReplyObject(reply);
    
        // 4. GET コマンドを実行
        reply = redisCommand(c, "GET mykey");
        if (reply == NULL) {
            printf("GET command failed: %s\n", c->errstr);
            redisFree(c);
            exit(1);
        }
    
        if (reply->type == REDIS_REPLY_STRING) {
            printf("GET mykey = %s\n", reply->str);
        } else if (reply->type == REDIS_REPLY_NIL) {
            printf("Key 'mykey' does not exist\n");
        } else {
            printf("GET returned unexpected type: %d, error: %s\n", reply->type, reply->str);
        }
        freeReplyObject(reply);
    
        // 5. 接続を閉じる
        redisFree(c);
        printf("Disconnected from Redis\n");
    
        return 0;
    }
  3. コンパイルと実行

    # コンパイル。-I と -L の後のパスを実際のインストール場所に合わせて調整してください
    gcc -o orca orca.c -I/usr/local/include/hiredis -L/usr/local/lib -lhiredis
    
    # 実行
    ./orca

DMS を使用した接続

Orca への接続

  1. Data Management (DMS) にログインします。

  2. 上部のメニューバーで、[データ資産] > [インスタンス管理] を選択します。

    image

  3. [追加] をクリックし、[その他のクラウド/セルフマネージド] を選択し、NoSQL データベースセクションから [Redis] を選択します。

    image

  4. [次へ] をクリックして、基本情報ページに移動します。以下のようにパラメーターを設定します。

    • [インスタンスソース][VPC リースライン] に設定します。[インスタンスリージョン]PolarDB クラスターが配置されているリージョンまたは近くのリージョンに設定します。[VPC ID]PolarDB クラスターの VPC に設定します。VPC ID は製品ページで確認できます。[ログオンアドレス] には、Orca エンドポイントを入力します。

    • [アクセスモード][セキュリティホスティング + 手動] に設定します。データベースアカウントとパスワードのフィールドに、Orca アカウントの認証情報を入力します。

    • 情報を入力した後、[接続テスト] をクリックします。テストが成功すると、成功メッセージが表示されます。

    image

  5. [次へ] をクリックして、[詳細情報] ページに移動します。必要に応じて設定を構成します。

    説明

    現在、Orca は SSL の有効化をサポートしていないことにご注意ください。

    image

  6. [送信] をクリックします。送信が成功すると、Orca インスタンスはセキュリティホスティング状態になります。

    image

データ管理

  1. 上部のメニューバーで [SQL ウィンドウ] をクリックし、セキュリティホスティング状態の Orca クラスターを選択します。

  2. 現在、Orca は 1 つの論理 Redis データベース DB0 のみをサポートしています。現在のデータベース DB0 が表示されない場合は、[辞書の更新/同期] をクリックします。

    image

  3. 異常が見つからなければ、DMS を使用して Orca を管理できます。

    image