PolarDB for MySQL は、Redis プロトコルと互換性のある Orca 機能を提供しており、主流の Redis クライアントを使用してデータベースに接続できます。このトピックでは、接続の準備について説明し、いくつかの一般的なプログラミング言語のクライアント接続コードサンプルを提供します。
事前準備
Orca 機能に接続する前に、次の準備が完了していることを確認してください。
-
PolarDB クラスターで Orca 機能が有効になっていること。
-
クライアントの IP アドレスまたは CIDR ブロックを PolarDB クラスターの ホワイトリスト に追加していること。
-
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> -
コードサンプル:パスワードパラメーターを 1 つしか受け付けない 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.ymlを使用した設定Spring 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 設定クラスを使用できます。このサンプルコードでは、基盤となるクライアントとして Lettuce を使用しており、ユーザー名とパスワードを個別に設定できます。
-
プロジェクトのファイル構造は次のとおりです。
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-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 " 形式を使用します 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 を選択します。[ログオンアドレス] には、Orca エンドポイントを入力します。
-
[アクセスモード]:[セキュリティホスティング + 手動] を選択します。作成した Orca アカウントのデータベースアカウントとパスワードを入力します。
-
情報を入力した後、テスト接続 をクリックします。エラーが発生しない場合、接続が成功したことを示すメッセージが表示されます。

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

-
提出する をクリックします。エラーが発生しない場合、Orca はセキュリティホスティング状態になります。

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

-
エラーが発生しない場合、DMS を使用して Orca を管理できます。
たとえば、[SQL コンソール] で
ping key01コマンドを実行します。key01が返された場合、接続は成功です。