PolarDB for MySQL の Orca 機能は Redis プロトコルと互換性があり、主要な Redis クライアントを使用してデータベースに接続できます。このガイドでは、前提条件と、いくつかの一般的なプログラミング言語のクライアント接続コードサンプルを説明します。
前提条件
Orca に接続する前に、次の前提条件を満たしていることを確認してください。
-
PolarDB クラスターで Orca 機能が有効になっていること。
-
クライアントの IP アドレスまたは CIDR ブロックが PolarDB クラスターのホワイトリストに追加されていること。
-
Orca 機能にアクセスするための専用の Orca アカウントが作成されていること。
-
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 での接続
-
redis-cli のインストール:redis-cli のインストールチュートリアル を参照して、クライアントデバイスにインストールします。
-
Orca への接続:次のコマンドを実行します。エンドポイントとポートは、実際の接続情報に置き換えてください。
redis-cli -h pz-****************.rwlb.rds.aliyuncs.com -p 6379 -
接続の認証:接続後、
AUTHコマンドを使用して認証します。次のいずれかのフォーマットを使用できます。プレースホルダーを実際の Orca アカウントとパスワードに置き換えてください。# フォーマット 1: ユーザー名とパスワードを個別に指定します。 AUTH orca_user orca_password # フォーマット 2: 連結したユーザー名とパスワードをパスワードとして指定します。 AUTH orca_user:orca_password戻り値が
OKの場合、接続と認証が成功したことを示します。
クライアントライブラリでの接続
アプリケーションから接続するには、次の例を使用してください。
Java (Jedis)
-
Maven 依存関係の追加:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency> -
コードサンプル: Jedis は単一のパスワードパラメータしか受け付けないため、
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)
-
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> -
コードサンプル: 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)
-
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> -
コードサンプル: Orca への接続を設定するには、次のいずれかの方法を選択できます。
application.ymlSpring Boot 2.x 以降では、
application.ymlでユーザー名とパスワードを個別に指定できます。この方法を推奨します。-
プロジェクトのファイル構造は次のとおりです。
test_redis/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ ├── MainApplication.java │ └── RedisTestRunner.java └── resources/ └── application.yml -
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 -
メインアプリケーションクラス
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); } } -
テストランナークラス
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 設定クラスを使用できます。次の例では
LettuceConnectionFactoryを使用しており、ユーザー名とパスワードを個別に指定できます。-
プロジェクトのファイル構造は次のとおりです。
test_redis/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ ├── config/ │ │ └── RedisConfig.java <-- コア設定クラス │ ├── MainApplication.java │ └── RedisTestRunner.java └── resources/ └── application.yml <-- このファイルは削除または空のままにできます。 -
コア設定クラス
RedisConfig.javaを作成します。このクラスでは、すべての接続情報を含むRedisConnectionFactoryBean を手動で作成および設定します。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; } } -
メインアプリケーションクラス
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); } } -
テストランナークラス
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 ==="); } }
-
Python (redis-py)
-
依存関係のインストール:
pip install redis -
コードサンプル:
redis-py4.2 以降は、個別のusernameパラメータをサポートしています。古いバージョンでは、username:password文字列を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)
-
依存関係のインストール:
go get github.com/go-redis/redis/v8 -
コードサンプル:
go-redisは、個別のUsernameフィールドをサポートしています (推奨)。古いバージョンでは、username:password文字列を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)
-
依存関係のインストール:
npm install redis -
コードサンプル:
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)
-
依存関係のインストール: 通常、この拡張機能はパッケージマネージャーを使用してインストールできます。たとえば、CentOS の場合:
sudo yum install php-redis -
コードサンプル:
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)
-
依存関係のインストール: ソースコードからコンパイルしてインストールします。
git clone https://github.com/redis/hiredis.git cd hiredis make && sudo make install -
コード例:
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); } // reply 自体がエラータイプであるかを確認します。 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); // 認証成功後、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 タイプの reply を返します。 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; } -
プログラムのコンパイルと実行:
# コンパイルします。-I と -L の後のパスは、インストール場所に応じて調整してください。 gcc -o orca orca.c -I/usr/local/include/hiredis -L/usr/local/lib -lhiredis # プログラムを実行します。 ./orca
DMS での接続
Orca への接続
-
追加 をクリックし、[サードパーティクラウド/セルフマネージド] を選択してから、NoSQL データベースセクションから [Redis] を選択します。

-
次へ をクリックして基本情報ページに移動します。次のようにパラメータを設定します。
-
インスタンスソース で [VPC PrivateLine] を選択します。インスタンスリージョン で、PolarDB クラスターが配置されているリージョンまたは近くのリージョンを選択します。[VPC ID] で、PolarDB クラスターの詳細ページから VPC ID を選択します。[ログオンアドレス] に、Orca エンドポイント を入力します。
-
アクセスモード で [アカウント + パスワードログイン] を選択します。Orca アカウントのデータベースアカウントとパスワードを入力します。
-
情報を入力した後、テスト接続 をクリックします。接続が成功すると、成功メッセージが表示されます。

-
-
次へ をクリックして [詳細情報] ページに移動し、必要に応じて設定を構成します。
説明現在、Orca は SSL 暗号化をサポートしていません。

-
提出する をクリックします。成功すると、Orca インスタンスはセキュア管理モードに入ります。

データ管理
-
上部メニューで、データ織り を選択し、管理対象の Orca クラスターを選択します。
-
現在、Orca は 1 つの論理 Redis データベース、DB0 のみをサポートしています。DB0 データベースが表示されない場合は、[辞書の更新/同期] をクリックします。

-
これで、DMS を使用して Orca を管理できます。
たとえば、[SQL コンソール] で
ping key01コマンドを実行します。戻り値としてkey01が返された場合、接続が成功したことを示します。