メインコンテンツまでスキップ

Redis Replication への接続

Redis Replication の database は 2 つの endpoint を提供しており、どちらに接続するかで failover 時のアプリケーションの挙動が変わります。

Endpointポート形式
Primary endpoint6379{vip}:6379 (例: 172.26.47.3:6379)
Advanced endpoint26379{ip_node1}:26379,{ip_node2}:26379,{ip_node3}:26379

Primary endpoint は Console Portal の database の Overview タブで確認できます。

Primary endpoint

Primary endpoint は常に現在の Redis Primary node を指し、failover が起きても変わりません。GETSETDELEXPIRE、Pub/Sub など標準的な Redis の操作に使います。

次の場合に適しています。

  • 標準的なアプリケーションからの接続。
  • シンプルな Redis client の実装。
  • Sentinel に対応していないシステム。

Advanced endpoint

Advanced endpoint は Redis Sentinel の endpoint です。Sentinel は Redis の node を監視し、障害を検知し、自動 failover を実行し、client にサービスディスカバリを提供します。failover が起きると Sentinel が新しい Primary を通知し、Sentinel 対応の client ライブラリが自動的に接続し直すため、こちら側で設定を変更する必要はありません。

次の場合に適しています。

  • High Availability の環境。
  • failover 後に自動で再接続する必要があるアプリケーション。
  • Sentinel に対応した高機能な Redis client。
  • トポロジの把握が必要な本番環境。

client ライブラリが Sentinel に対応している場合は、Primary endpoint ではなく Advanced endpoint に接続してください。

どちらの endpoint を使うべきか

用途推奨する endpoint
標準的なアプリケーションからの接続Primary endpoint
Sentinel 対応の client ライブラリを使うアプリケーションAdvanced endpoint
redis-cliPrimary endpoint

接続例

redis-cli

redis-cli は Sentinel に対応していません。一度に 1 つのホストとポートにしか接続できず、Sentinel node の自動検出もできないため、Primary endpoint から接続してください。

redis-cli -h {vip} -p 6379 -a {redis_password}

Python (redis-py)

pip install redis
from redis.sentinel import Sentinel

sentinel = Sentinel(
[
("{ip_node1}", 26379),
("{ip_node2}", 26379),
("{ip_node3}", 26379),
],
socket_timeout=2,
)

redis_master = sentinel.master_for(
service_name="mymaster",
password="{redis_password}",
decode_responses=True,
)

redis_master.set("test", "hello")
print(redis_master.get("test"))

Node.js (ioredis)

npm install ioredis
const Redis = require("ioredis");

const redis = new Redis({
sentinels: [
{ host: "ip_node1", port: 26379 },
{ host: "ip_node2", port: 26379 },
{ host: "ip_node3", port: 26379 },
],
name: "mymaster",
password: "redis_password",
});

async function test() {
await redis.set("test", "hello");
const value = await redis.get("test");
console.log(value);
}

test();

Spring Boot

Java の Spring Boot アプリケーションでは、FPT は Lettuce または Jedis client と組み合わせた Spring Data Redis を推奨します。Sentinel の master 名と Sentinel node の一覧を application.yml または application.properties に定義してください。

spring:
data:
redis:
password: redis_password
sentinel:
master: mymaster
nodes:
- ip_node1:26379
- ip_node2:26379
- ip_node3:26379
spring.data.redis.password=redis_password
spring.data.redis.sentinel.master=mymaster
spring.data.redis.sentinel.nodes=ip_node1:26379,ip_node2:26379,ip_node3:26379
注記

古いバージョンの Spring Boot では spring.data.redis.* ではなく spring.redis.* の接頭辞を使います。使用しているバージョンではどちらが該当するか確認してください。

次のステップ