このトピックでは、Tair (および Redis Open-Source Edition) インスタンスへの接続方法について説明します。インスタンスに接続するには、まずネットワーク接続を確立し、ホワイトリストを設定する必要があります。
ネットワーク接続の確立とホワイトリストの設定
インスタンスに接続する前に、クライアントとインスタンス間のネットワーク接続を確立し、IP ホワイトリストを設定する必要があります。詳細については、「接続の準備」をご参照ください。
Tair (および Redis Open-Source Edition) への接続
以下の表に、インスタンスへの接続に必要なパラメーターを示します。
パラメーター | 説明 | パラメーター値の取得方法 |
hostname | エンドポイント |
|
port | ポート番号 | デフォルトのポート番号は 6379 です。カスタムポート番号を使用することもできます。詳細については、「エンドポイントまたはポートの変更」をご参照ください。 |
password | パスワード | アカウントの種類に基づいてアカウントとパスワードを入力します:
パスワードを忘れた場合、またはパスワードを設定していない場合は、パスワードをリセットできます。詳細については、「パスワードの変更またはリセット」をご参照ください。 |
redis-cli を使用した接続
お使いのデバイスに redis-cli がインストールされていない場合は、以下の手順に従ってください。
インスタンスに接続します:
redis-cli がインストールされているディレクトリに移動します。
Linux
`..\redis-7.2.0\src` ディレクトリに移動します。例:
cd /home/redis-7.2.0/src。macOS
redis-cli がインストールされているディレクトリ (
cd /opt/homebrew/binなど) に移動します。Windows
コマンドラインを開き、redis-cli がインストールされているディレクトリに移動します。
次のコマンドを実行して、redis-cli を使用してインスタンスに接続します:
./redis-cli -h <hostname> -p <port> [-c]説明Windows では、PowerShell を使用して redis-cli を起動するコマンドは
.\redis-cli -h hostname -p port [-c]です。コマンドの例:
デフォルトのエンドポイント: このエンドポイントは、標準アーキテクチャインスタンスのエンドポイントやクラスターアーキテクチャインスタンスのプロキシエンドポイントなど、デフォルトのエンドポイントを使用して接続するシナリオに適しています。
./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379クラスターインスタンスの直接接続エンドポイント: このエンドポイントは、直接接続エンドポイントを使用してクラスターアーキテクチャインスタンスに接続するシナリオに適しています。
./redis-cli -h r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com -p 6379 -c
次のコマンドを実行してパスワードを確認します:
AUTH <password>例:
AUTH testaccount:Rp829dlwa
コードを使用した接続
Spring Data Redis
この例では、ビルドに Maven を使用します。Lettuce または Jedis クライアントを手動でダウンロードすることもできます。
コンパイラを開き、プロジェクトを作成します。
次の
pomファイルを追加して、Lettuce または Jedis をダウンロードします。重要Lettuce を使用する場合は、6.3.0.RELEASE 以降を使用し、TCP_USER_TIMEOUT パラメーターを設定することをお勧めします。これにより、Lettuce クライアントでのブラックホールフィルタリングが防止されます。
<?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>Spring Data Redis エディターに次のコードを入力し、コメントに基づいて変更します。
この例では、Spring Data Redis 2.4.2 を使用します。
Jedis を使用した Spring Data Redis
@Configuration public class RedisConfig { @Bean JedisConnectionFactory redisConnectionFactory() { //この例は接続テスト専用です。本番環境では、接続情報を設定ファイルに保存し、@Value アノテーションを使用して情報を取得することをお勧めします。 //エンドポイント (hostName) とポート番号 (port) は、[インスタンス情報] ページの [接続情報] セクションから取得できます。クライアントのネットワーク環境に基づいて、VPC またはパブリック接続を選択します。 RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("r-8vbwds91ie1rdl****.redis.zhangbei.rds.aliyuncs.com", 6379); //パスワードを username:password の形式で入力します。たとえば、ユーザー名が testaccount でパスワードが Rp829dlwa の場合、パスワードとして testaccount:Rp829dlwa を入力します。 //ユーザー名またはパスワードを忘れた場合は、インスタンス詳細ページの左側のナビゲーションウィンドウで [アカウント管理] をクリックして、パスワードをリセットするか、アカウントを作成します。 config.setPassword(RedisPassword.of("username:password")); 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); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } }Lettuce を使用した Spring Data Redis (TCP_USER_TIMEOUT パラメーターの設定を含む)
@Configuration public class BeanConfig { /** * TCP キープアライブを有効にし、次の 3 つのパラメーターを設定します: * 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"); // TCP KeepAlive の設定 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; } }
Jedis
この例では、ビルドに Maven を使用します。Jedis クライアントを手動でダウンロードすることもできます。
コンパイラを開き、プロジェクトを作成します。
pom.xmlファイルに次のコードを追加します。この例では、Jedis 4.3.0 を使用します。
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.3.0</version> </dependency>エディターに次のコードを入力し、コメントに基づいて変更します:
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(); // 要件に基づいて最大アイドル接続数を指定します。この値は、Redis インスタンスでサポートされている最大接続数を超えることはできません。 config.setMaxIdle(200); // 要件に基づいて最大接続数を指定します。この値は、Redis インスタンスでサポートされている最大接続数を超えることはできません。 config.setMaxTotal(300); config.setTestOnBorrow(false); config.setTestOnReturn(false); // hostname と password の値をインスタンスのエンドポイントとパスワードに置き換えます。 String hostname = "r-bp1s1bt2tlq3p1****pd.redis.rds.aliyuncs.com"; // デフォルトアカウントの場合は、パスワードを直接入力できます。新しいアカウントの場合は、user:password の形式でパスワードを入力します。たとえば、新しいアカウントが testaccount でパスワードが Rp829dlwa の場合、testaccount:Rp829dlwa と入力します。 String password = "r-bp1s1bt2tlq3p1****:Database123"; JedisPool pool = new JedisPool(config, hostname, 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(); // アプリケーションが終了し、リソースを破棄する必要がある場合は、このメソッドを呼び出します。このメソッドは接続を切断し、リソースを解放します。 } }上記のプロジェクトを実行します。次の出力が期待されます:
bar [bike, car]
redis-py
redis-py クライアントをダウンロードしてインストールします。
Python エディターに次のコードを入力し、コメントに基づいて変更します。
この例では、Python 3.9 と redis-py 4.4.1 を使用します。
#!/usr/bin/env python #-*- coding: utf-8 -*- import redis # hostname と port の値をインスタンスのエンドポイントとポート番号に置き換えます。 hostname = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com' port = 6379 # pwd の値をインスタンスのパスワードに置き換えます。 # デフォルトアカウントの場合は、パスワードを直接入力できます。新しいアカウントの場合は、user:password の形式でパスワードを入力します。たとえば、新しいアカウントが testaccount でパスワードが Rp829dlwa の場合、testaccount:Rp829dlwa と入力します。 password = 'testaccount:Rp829dlwa' r = redis.Redis(host=hostname, port=port, password=password) # 接続が確立されたら、データベース操作を実行できます。次のコードは、SET と GET の使用方法の例です。 r.set('foo', 'bar') print(r.get('foo'))上記のプロジェクトを実行します。次の出力が期待されます:
b'bar'
PhpRedis
PhpRedis クライアントをダウンロードしてインストールします。
PHP エディターに次のコードを入力し、コメントに基づいて変更します。
この例では、PHP 8.2.1 と PhpRedis 5.3.7 を使用します。
<?php /* hostname と port の値をインスタンスのエンドポイントとポート番号に置き換えます。 */ $hostname = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com"; $port = 6379; /* user と password の値をインスタンスのアカウントとパスワードに置き換えます。 */ $user = "testaccount"; $password = "Rp829dlwa"; $redis = new Redis(); if ($redis->connect($hostname, $port) == false) { die($redis->getLastError()); } if ($redis->auth([$user, $password]) == false) { die($redis->getLastError()); } /* 認証後、データベース操作を実行できます。次のコードは、SET と GET の使用方法の例です。 */ if ($redis->set("foo", "bar") == false) { die($redis->getLastError()); } $value = $redis->get("foo"); echo $value; ?>上記のコードを実行します。
説明一般的なエラーと解決策:
Cannot assign requested address: エラーの原因と解決策については、「「Cannot assign requested address」エラーが返された場合の対処方法」をご参照ください。redis protocol error, got ' ' as reply type byte: PhpRedis クライアントのバージョンを更新してください。詳細については、「GitHub」をご参照ください。
C または C++
C クライアントをダウンロードしてインストールします。
C または C++ エディターに次のコードを入力し、コメントに基づいて変更します。
この例では、hiredis 1.1.0 を使用します。
#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 seconds 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); /* キーを設定 */ reply = redisCommand(c,"SET %s %s", "foo", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* バイナリセーフ API を使用してキーを設定 */ reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); printf("SET (binary API): %s\n", reply->str); freeReplyObject(reply); /* GET と 2 つの INCR を試す */ reply = redisCommand(c,"GET foo"); printf("GET foo: %s\n", reply->str); freeReplyObject(reply); 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); /* 0 から 9 までの数値のリストを作成 */ 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; }コードをコンパイルします。
gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredisテスト実行を実行し、インスタンスに接続します。
./example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 r-bp10noxlhcoim2**** password
.NET
StackExchange.Redis 2.7.20 以降をダウンロードしてインストールします。詳細については、「StackExchange.Redis の更新に関する通知」をご参照ください。
重要ServiceStack Redis または CSRedis クライアントは使用しないことをお勧めします。
ServiceStack Redis を使用し、クライアントに関連する問題が発生した場合は、ServiceStack からテクニカルサポートを購入する必要があります。
CSRedis クライアントのサポートは終了しました。
StackExchange.Redis エディターに次のコードを入力し、コメントに基づいて変更します。
この例では、StackExchange.Redis 2.7.20 を使用します。
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; }説明ConfigurationOptions は StackExchange.Redis のコアです。アプリケーション全体で共有および再利用され、シングルトンとして設定する必要があります。パラメーター設定の詳細については、「ConfigurationOptions」をご参照ください。
GetDatabase()によって返されるオブジェクトは軽量です。使用するたびに ConnectionMultiplexer オブジェクトから取得できます。redisConn = getRedisConn(); var db = redisConn.GetDatabase();
node-redis
node-redis クライアントをダウンロードしてインストールします。
node-redis クライアントに次のコードを入力し、コメントに基づいて変更します。
この例では、Node.js 19.4.0 と node-redis 4.5.1 を使用します。
import { createClient } from 'redis'; // インスタンスのポート番号、エンドポイント、アカウント、パスワードを設定します。 const hostname = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'; const port = 6379; const username = 'testaccount'; // パスワードに特殊文字 (!@#$%^&*()+-=_) が含まれている場合は、encodeURIComponent を使用してパスワードをエンコードすることをお勧めします: password = encodeURIComponent(password) const password = 'Rp829dlwa'; const client = createClient({ // redis://[[username]:[password]@[hostname][:port]/[db-number] url: `redis://${username}:${password}@${hostname}:${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();説明SyntaxError: Cannot use import statement outside a moduleエラーが報告された場合は、.jsファイルの拡張子を.mjsに変更し、ファイルを呼び出すときに--experimental-modulesオプションを追加します。例:node --experimental-modules redis.mjs。
Go-redis
Go-Redis クライアントをダウンロードしてインストールします。
Go-redis エディターに次のコードを入力し、コメントに基づいて変更します。
この例では、Go 1.18.5 と Go-redis 8.11.5 を使用します。
package main import ( "github.com/go-redis/redis" "fmt" ) func ExampleClient() { client := redis.NewClient(&redis.Options{ // インスタンスのエンドポイントとポートに置き換えます。 Addr: "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379", // インスタンスのパスワードに置き換えます。 Password: "testaccount:Rp829dlwa", DB: 0, // デフォルトの DB を使用 }) // 次のコードは、SET と GET の使用方法の例です。 err := client.Set("foo", "bar", 0).Err() if err != nil { panic(err) } val, err := client.Get("foo").Result() if err != nil { panic(err) } fmt.Println("set : foo -> ", val) } func main() { ExampleClient() }
Lettuce
DMS を使用した接続
コンソールにログインし、インスタンスページに移動します。上部のナビゲーションバーで、管理するインスタンスが存在するリージョンを選択します。次に、インスタンスを見つけてインスタンス ID をクリックします。
ページの右上隅にある データベースにログインする をクリックします。
DMS コンソールで、ログイン方法を設定します。
アクセス方法
説明
[ユーザー名とパスワードでログイン]
(推奨)
データベースアカウントと対応するパスワードを入力します。データベースアカウントの作成方法については、「アカウントの作成と管理」をご参照ください。
説明デフォルトでは、インスタンスにはインスタンス ID (r-bp10noxlhcoim2**** など) の名前が付いたデータベースアカウントが付属しています。このアカウントを使用してログインできます。アカウントのパスワードは、インスタンスの作成時に指定されました。
[パスワードなしのログイン]
インスタンスでパスワードなしのアクセスが有効になっている場合は、パスワードを使用せずにインスタンスにログインできます。詳細については、「VPC 経由でのパスワードなしのアクセスを有効にする」をご参照ください。
[パスワードでログイン]
インスタンスの作成時に指定したパスワードを使用してインスタンスにログインします。パスワードは、インスタンス ID の名前が付いたデータベースアカウント用に作成されます。
説明パスワードを忘れた場合は、リセットできます。詳細については、「パスワードの変更またはリセット」をご参照ください。
他のパラメーターはデフォルト値のままにしておくことができます。
[ログイン] をクリックします。
DMS サーバーの IP アドレスをインスタンスのホワイトリストに追加していない場合は、ダイアログボックスが表示されます。[ホワイトリストを設定] をクリックする必要があります。システムは、インスタンスに ali_dms_group という名前のホワイトリストグループを作成し、このグループに DMS サーバーの IP アドレスを追加します。
ログイン後、[SQLConsole] タブのテキストボックスにコマンドを入力して実行できます。たとえば、DBSIZE コマンドを実行して、現在のデータベース内のキーの数をクエリできます。
Tair (および Redis Open-Source Edition) でサポートされているコマンドの詳細については、「コマンドの概要」をご参照ください。
その他の接続方法
直接接続モードを使用してクラスターインスタンスに接続する: クラスターインスタンスの直接接続エンドポイントをリクエストして、バックエンドのデータシャードに直接アクセスできます。これは、ネイティブの Redis クラスターへの接続に似ています。プロキシモードと比較して、直接接続モードはリクエストがプロキシノードを通過しないため、応答時間が短縮されます。
TLS (SSL) 暗号化を有効にしてインスタンスに接続する: TLS 暗号化機能を有効にして、データリンクのセキュリティを向上させ、データ整合性を確保できます。
Sentinel 互換モードを使用してインスタンスに接続する: Tair は Sentinel 互換モードを提供します。このモードを有効にすると、クライアントはネイティブの Redis Sentinel に接続するのと同じ方法でインスタンスに接続できます。