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 をインストールします。詳細については、「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_passwordOKが返された場合、接続と認証は成功です。
各種言語のクライアントを使用した接続
ご利用のアプリケーションのプログラミング言語に応じて、以下の例を参照して接続してください。
Java (Jedis)
依存関係の設定を追加します (Maven):
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency>コード例: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)
依存関係の設定を追加します (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.ymlによる設定Spring Boot 2.x 以降では、
application.ymlでユーザー名とパスワードを個別に指定できます。この方法を推奨します。プロジェクトのファイル構造は次のとおりです。
test_redis/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ ├── MainApplication.java │ └── RedisTestRunner.java └── resources/ └── application.ymlapplication.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 設定クラスを使用できます。下位レイヤーで Jedis が使用されるため、認証には引き続きユーザー名とパスワードを連結する必要があります。
プロジェクトのファイル構造は次のとおりです。
test_redis/ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ ├── config/ │ │ └── RedisConfig.java <-- コア設定クラス │ ├── MainApplication.java │ └── RedisTestRunner.java └── resources/ └── application.yml <-- このファイルは削除するか、空のままにすることができますコア設定クラス
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; } }メインの起動クラス
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-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)
依存関係をインストールします。
go get github.com/go-redis/redis/v8コード例:
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)
依存関係をインストールします。
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); } // 応答自体がエラータイプかどうかを確認 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; }コンパイルと実行
# コンパイル。-I と -L の後のパスを実際のインストール場所に合わせて調整してください gcc -o orca orca.c -I/usr/local/include/hiredis -L/usr/local/lib -lhiredis # 実行 ./orca
DMS を使用した接続
Orca への接続
[追加] をクリックし、[その他のクラウド/セルフマネージド] を選択し、NoSQL データベースセクションから [Redis] を選択します。

[次へ] をクリックして、基本情報ページに移動します。以下のようにパラメーターを設定します。
[インスタンスソース] を [VPC リースライン] に設定します。[インスタンスリージョン] を PolarDB クラスターが配置されているリージョンまたは近くのリージョンに設定します。[VPC ID] を PolarDB クラスターの VPC に設定します。VPC ID は製品ページで確認できます。[ログオンアドレス] には、Orca エンドポイントを入力します。
[アクセスモード] を [セキュリティホスティング + 手動] に設定します。データベースアカウントとパスワードのフィールドに、Orca アカウントの認証情報を入力します。
情報を入力した後、[接続テスト] をクリックします。テストが成功すると、成功メッセージが表示されます。

[次へ] をクリックして、[詳細情報] ページに移動します。必要に応じて設定を構成します。
説明現在、Orca は SSL の有効化をサポートしていないことにご注意ください。

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

データ管理
上部のメニューバーで [SQL ウィンドウ] をクリックし、セキュリティホスティング状態の Orca クラスターを選択します。
現在、Orca は 1 つの論理 Redis データベース DB0 のみをサポートしています。現在のデータベース DB0 が表示されない場合は、[辞書の更新/同期] をクリックします。

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

