The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.
このページを編集

Redis エクステンションのリファレンスガイド

stable

Redis は、データベース、キャッシュ、ストリーミングエンジン、メッセージブローカーとして使用されるインメモリーデータストアです。Quarkus Redis エクステンションを使用すると、Quarkus アプリケーションと Redis を統合できます。

このエクステンションを使用するには、ユーザーが Redis に精通していること、特にコマンドのメカニズムとその構成方法を理解していることが必要です。通常、以下を推奨します。

  1. Redis を紹介する インタラクティブなチュートリアル

  2. Redis コマンドを説明し、リファレンスドキュメントへのリンクが掲載されている コマンドリファレンス

このエクステンションは、命令型とリアクティブ型の API、および低レベルと高レベルの (タイプセーフな) クライアントを提供します。

1. Redis クライアントの使用

このエクステンションを使用する場合は、最初に io.quarkus:quarkus-redis エクステンションを追加する必要があります。pom.xml ファイルに、以下を追加します。

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-redis-client</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-redis-client")

この依存関係があれば、次に Redis クライアントや データソース (高レベル、タイプセーフの API) を注入できます。以下に例を示します。

import io.quarkus.redis.datasource.RedisDataSource;

// ...
@Inject RedisAPI lowLevelClient;
@Inject RedisDataSource highLevelApi;

quarkus-redis エクステンションで提供されるさまざまな API の詳細については、1 つのエクステンション、複数の API セクションを参照してください。

Redis をキャッシュバックエンドとして使用するには、Redis キャッシュバックエンドリファレンス を参照してください。

2. 1 つのエクステンション、複数の API

このエクステンションは、Redis と対話する複数の方法を提供します。

  • 低レベルの Vert.x クライアント: 完全にリアクティブで、ノンブロッキングかつ非同期なクライアントです。詳細は Vert.x Redis クライアントドキュメント を参照してください。2 つの API (io.vertx.redis.client.Redis および io.vertx.redis.client.RedisAPI) が公開されています。接続を自分で管理する必要がある場合を除き、通常は後者を利用することになります。

  • Vert.x API の 低レベルの Mutiny バリアント: 以前のものとは異なり、Mutiny API を公開し、リアクティブ型と命令型の両方のメソッド (接尾辞は andAwait()) が提供されます。2 つの API (io.vertx.mutiny.redis.client.Redis および io.vertx.mutiny.redis.client.RedisAPI) が公開されています。自分で接続を管理する必要がある場合を除いて、通常は後者を使用します。

  • 高レベルの リアクティブデータソース: Redis と対話するための、タイプセーフな高レベル API です。この API は完全にリアクティブで非同期です。これは、Mutiny API を公開します。io.quarkus.redis.datasource.ReactiveRedisDataSource インターフェイスを公開します。

  • 高レベルの 命令型データソース: Redis と対話するための、タイプセーフな高レベル API です。これはリアクティブデータソースの命令型バリアントです。io.quarkus.redis.datasource.RedisDataSource インターフェイスを公開します。

適切な API を選択できるように、いくつかの推奨事項を以下に示します。

  • Redis と統合する命令型 (classic) の Quarkus アプリケーションを構築する場合: io.quarkus.redis.datasource.RedisDataSource を使用します。

  • Redis と統合したリアクティブな Quarkus アプリケーションを構築する場合: io.quarkus.redis.datasource.ReactiveRedisDataSource を使用します。

  • 細かい制御が必要な場合や、汎用的な方法でコマンドを実行する場合は: io.vertx.mutiny.redis.client.RedisAPI を使用します。

  • 既存の Vert.x コードがある場合は: io.vertx.redis.client.RedisAPI を使用します。

  • カスタムコマンドを発行する必要がある場合は、データソース (リアクティブ型または命令型) または io.vertx.mutiny.redis.client.Redis を使用することができます。

3. デフォルトおよび名前付きクライアントを注入

このエクステンションでは、デフォルトの Redis クライアント/データソースまたは 名前付き ソースを設定できます。後者は、複数の Redis インスタンスに接続する必要がある場合に不可欠となります。

デフォルトの接続は、quarkus.redis.* プロパティーを使用して設定されます。たとえば、デフォルトの Redis クライアントを設定するには、以下を使用します。

quarkus.redis.hosts=redis://localhost/

デフォルトの接続を使用する場合、プレーン @Inject を使用してさまざまな API を注入できます。

@ApplicationScoped
public class RedisExample {
    @Inject ReactiveRedisDataSource reactiveDataSource;
    @Inject RedisDataSource redisDataSource;
    @Inject RedisAPI redisAPI;
    // ...
}
一般的には、1 つだけ注入します。先ほどのスニペットは単なる一例です。

名前付き クライアントは quarkus.redis.<name>.* プロパティーを使用して設定されます。

quarkus.redis.my-redis-1.hosts=redis://localhost/
quarkus.redis.my-redis-2.hosts=redis://my-other-redis:6379

API にアクセスするには、@RedisClientName 修飾子を使用する必要があります。

@ApplicationScoped
public class RedisExample {
    @Inject @RedisClientName("my-redis-1") ReactiveRedisDataSource reactiveDataSource;
    @Inject @RedisClientName("my-redis-2") RedisDataSource redisDataSource;
    // ...
}
@RedisClientName を使用する場合、@Inject アノテーションを省略することができます。

3.1. Redis クライアントの有効化または無効化

Redis クライアントがビルド時に設定され、その URL が実行時に設定されている場合、デフォルトでアクティブになります。Quarkus は、アプリケーションの起動時に対応する Redis クライアントを起動します。

実行時に Redis クライアントを非アクティブ化するには、次のいずれかを実行します。

  • quarkus.redis[.optional name].hosts または quarkus.redis[.optional name].hosts-provider-name を設定しないでください。

  • quarkus.redis[.optional name].activefalse に設定します。

Redis クライアントがアクティブでない場合:

  • Redis クライアントは、アプリケーションの起動中に Redis への接続を試みません。

  • Redis クライアントは ヘルスチェック を提供しません。

  • @Inject ReactiveRedisDataSource redis@Inject RedisDataSource redis など、Redis クライアントを含む静的な CDI 注入ポイントがあると、アプリケーションの起動が失敗します。

  • CDI.getBeanContainer()Arc.instance()、または注入された Instance<ReactiveRedisDataSource> を介した Redis クライアントの動的な取得は、例外をスローします。

  • Redis クライアントを使用する他の Quarkus エクステンションが、アプリケーションの起動を失敗させる可能性があります。

この機能は、アプリケーションが実行時に事前定義されたセットから Redis クライアントを動的に選択する必要がある場合に特に役立ちます。

実行時選択のための複数の Redis クライアント設定の例
quarkus.redis.one.active=false
quarkus.redis.one.hosts=redis://localhost:64251

quarkus.redis.two.active=false
quarkus.redis.two.hosts=redis://localhost:64251
import io.quarkus.arc.InjectableInstance;

@ApplicationScoped
public class MyConsumer {
    @Inject
    @RedisClientName("one")
    InjectableInstance<ReactiveRedisDataSource> one;
    @Inject
    @RedisClientName("two")
    InjectableInstance<ReactiveRedisDataSource> two;

    public void doSomething() {
        ReactiveRedisDataSource redis = one.getActive();
        // ...
    }
}

実行時 quarkus.redis.one.active=true を設定すると、Redis クライアント one のみが利用可能になります。実行時に quarkus.redis.two.active=true を設定すると、Redis クライアント two のみが利用可能になります。

Redis クライアント (デフォルトまたは名前付き) は、実行時注入で考慮されるために、常にビルド時に検出可能である必要があります。これは、@RedisClientName で Redis クライアント名を注入することで可能です。Redis クライアント名がアクティブまたは非アクティブである可能性がある場合、ラッパー InjectableInstance<> を使用する必要があります。そうしないと、Redis クライアントが非アクティブの場合、Quarkus は起動時に例外をスローします。あるいは、Redis クライアントは設定を介して検出することもできます。

4. Redis サーバーへの接続

Redis エクステンションは、4 つの異なるモードで動作できます。

  • シンプルなクライアント (おそらくほとんどのユーザーが必要としているもの)。

  • Sentinel (高可用性モードで Redis を使用する場合)。

  • クラスター (Redis を Clustered モードで動作させる場合)。

  • レプリケーション (シングルシャード、1 ノード書き込み、マルチ読み取り)。

接続 URL は、以下のように quarkus.redis.hosts (または quarkus.redis.<name>.hosts) で設定されます。

quarkus.redis.hosts=redis://[:password@]host[:port][/db-number]

4.1. Unix ソケットの使用

unix-socket を使用する場合、以下が必要です。

quarkus.redis.hosts=unix://[:password@]/domain/docker.sock[?select=db-number]

4.2. Sentinel モードの使用

Sentinel を使用する場合、複数の host urls を渡し、クライアントのタイプを sentinel に設定する必要があります。

quarkus.redis.hosts=redis://localhost:5000,redis://localhost:5001,redis://localhost:5002
quarkus.redis.client-type=sentinel

# Optional
quarkus.redis.master-name=my-sentinel # Default is mymaster
quarkus.redis.role=master # master is the default

ここでのホスト URL は sentinel サーバーである必要があります。クライアントは、マスターセットの識別子として master-name を使用して、sentinel の 1 つから実際の Redis サーバー (role に応じてマスターまたはレプリカ) の URL を取得します。

実際には、 quarkus.redis.role=sentinel を設定する必要はないことに注意してください。この設定は、Redis クライアントが、sentinel によって保護されている実際の Redis サーバーではなく、sentinel サーバーの 1 つで直接コマンドを実行することを意味します。

4.2.1. 自動フェイルオーバー

sentinel モードでは、_ マスター _ 接続の自動フェイルオーバーを設定できます。

quarkus.redis.auto-failover=true

有効にすると、sentinel クライアントは 1 つの sentinel ノードへの接続を追加で作成し、フェイルオーバーイベントを監視します。新しいマスターが選出されると、古いマスターへのすべての接続が自動的に閉じられ、新しいマスターへの新しい接続が作成されます。自動フェイルオーバーは、通常のコマンドを実行する接続には意味がありますが、Redis pub/sub チャネルをサブスクライブするために使用される接続には意味がありません。

古いマスターが失敗してから新しいマスターが選出されるまでの短期間に、既存の接続ですべての操作が一時的に失敗することに注意してください。新しいマスターが選出されると、接続は自動的にフェイルオーバーされ、再び動作を開始します。

4.3. クラスターモードの使用

Redis をクラスターモードで使用する場合、複数の ホスト urls を渡し、クライアントのタイプを cluster に設定し、 replicas モードを設定する必要があります。

quarkus.redis.hosts=redis://localhost:7000,redis://localhost:7001,redis://localhost:7002
quarkus.redis.client-type=cluster

# Optional
quarkus.redis.replicas=share # defaults to "never"

ここでのホスト URL は、クラスターメンバーの一部である必要があります。クライアントは既知のサーバーの 1 つから完全なクラスタートポロジーを取得するため、すべてのクラスターメンバーを設定する必要はありません。ただし、1 つのノードだけではなく、少なくとも 2 つまたは 3 つのノードを設定することを推奨します。

デフォルトでは、すべてのコマンドはマスターノードに送信されます (コマンドにキーがある場合は、キーを所有するシャードのマスターノード、それ以外の場合はランダムマスターノード)。Redis クライアントを設定して、レプリカノードに読み取り専用コマンド (クエリー) を送信することが可能です。quarkus.redis.replicas 設定プロパティーを次のように設定します。

  • never: レプリカノードは使用せず、常にマスターノードにクエリーを送信します (これがデフォルトです)。

  • always: 常にレプリカノードを使用します (シャード内にレプリカが複数ある場合は無作為に選択されます)。マスターノードにクエリーを送信しません。

  • share: マスターノードとレプリカノードを使用してクエリーを実行します (各クエリーの特定のノードは無作為に選択されます)。

Redis のレプリケーションは非同期であるため、レプリカノードはマスターノードより遅れる可能性があることに注意してください。

4.4. レプリケーションモードの使用

レプリケーションモードを使用する場合、単一のホスト URL を渡し、タイプを replication に設定する必要があります。

quarkus.redis.hosts=redis://localhost:7000
quarkus.redis.client-type=replication

# Optional
quarkus.redis.replicas=share # defaults to "never"

デフォルトでは、すべてのコマンドはマスターノードに送信されます。Redis クライアントを設定して、レプリカノードに読み取り専用コマンド (クエリー) を送信することが可能です。quarkus.redis.replicas 設定プロパティーを次のように設定します。

  • never: レプリカノードは使用せず、常にマスターノードにクエリーを送信します (これがデフォルトです)。

  • always: 常にレプリカノードを使用します (レプリカが複数ある場合はランダムに選択されます)。マスターノードにクエリーを送信しません。

  • share: マスターノードとレプリカノードを使用してクエリーを実行します (各クエリーの特定のノードは無作為に選択されます)。

Redis のレプリケーションは非同期であるため、レプリカノードはマスターノードより遅れる可能性があることに注意してください。

4.4.1. 静的トポロジー

レプリケーションモードでは、Redis クライアントを再設定してトポロジーの自動検出をスキップできます。

quarkus.redis.topology=static

静的トポロジーでは、設定内の最初のノードは マスター ノードであると見なされ、残りのノードは レプリカ であると見なされます。ノードは検証されません。静的構成が正しいことを確認するのは、アプリケーション開発者の責任です。

通常は、トポロジーの自動検出が優先されることに注意してください。静的設定は必要な場合にのみ使用してください。そのようなケースの 1 つが、Amazon Elasticache for Redis (クラスターモードが無効) です。

  • マスターノードは プライマリーエンドポイント に設定し、

  • 1 つのレプリカノードを リーダーエンドポイント に設定する必要があります。

Elasticache for Redis (クラスターモードが無効) のリーダーエンドポイントは、レプリカの 1 つを参照する CNAME レコードに対して解決されるドメイン名であることに注意してください。リーダーエンドポイントが解決する CNAME レコードは、時間の経過とともに変化します。この形式の DNS ベースの負荷分散は、DNS 解決キャッシュおよび接続プールでは正しく機能しません。その結果、一部のレプリカが十分に活用されない可能性があります。

4.5. Redis Cloud への接続

Redis Cloud に接続するためには、以下のプロパティーが必要です。

quarkus.redis.hosts=<the redis cloud url such as redis://redis-12436.c14.us-east-1-3.ec2.cloud.redislabs.com:12436>
quarkus.redis.password=<the password>

4.6. TLS の使用

TLS を使用するには、以下を実施してください:

  1. quarkus.redis.tls.enabled=true プロパティーを設定するか、 TLS レジストリー を使用します (推奨)。

  2. URL が rediss:// (2つの s を含む) で始まるようにしてください。

TLS レジストリーを使用する場合は、他の TLS 設定との競合を避けるために、名前付き設定を使用する必要があります。

quarkus.tls.redis.trust-store.p12.path=client.p12
quarkus.tls.redis.trust-store.p12.password=secret

quarkus.redis.tls-configuration-name=redis # Reference the named configuration
デフォルトのホスト名検証は NONE に設定されており、この設定ではホスト名は検証されません。この動作は、 quarkus.redis.tls.hostname-verification-algorithm プロパティーを、例えば HTTPS に設定して変更できます。

4.7. 認証の設定

Redis のパスワードは、 redis:// URL で設定するか、 quarkus.redis.password プロパティーで設定することができます。後者の方法、そして可能であればシークレットや環境変数を使ってパスワードを設定することをお勧めします。

関連する環境変数は QUARKUS_REDIS_PASSWORD で、名前付きクライアントの場合は QUARKUS_REDIS_<NAME>_PASSWORD となります。

4.8. 接続プール

Redis への接続は常にプールされます。デフォルトでは、プール内の接続の最大数は 6 です。これは quarkus.redis.max-pool-size を使用して設定できます。

接続プールが枯渇すると、接続を取得しようとする試行はキューに入れられます。デフォルトでは、Redis 接続の取得を待つキュー内の最大試行回数は 24 です。これは quarkus.redis.max-pool-waiting を使用して設定できます。

特定のコマンドを実行すると、サーバー側の状態と接続の動作が変更されます。このような接続は再利用できず、切断されたときにプールに戻されるのではなく、完全に切断されます。この動作を行うコマンドは次のとおりです。

  • サブスクリプションコマンド (SUBSCRIBEUNSUBSCRIBE など)

  • SELECT

  • AUTH

5. Redis データソースの使用

Quarkus は、Redis 上で高レベルの API を公開します。この API はタイプセーフで Redis コマンド編成 から継承された グループ の概念を中心とした構造となっています。この API を使用すると、Redis コマンドをより便利かつ安全に実行することができます。

5.1. データソースの注入

設定された各 Redis クライアントに対して、2 つの Redis データソースが公開されます。

  • io.quarkus.redis.datasource.RedisDataSource - 命令型 (ブロッキング) Redis データソース。各操作は、応答を受信するか、タイムアウトに達するまでブロックされます。

  • io.quarkus.redis.datasource.ReactiveRedisDataSource - Uni<X> または Multi<X> を返すリアクティブ型 Redis データソース。

デフォルトの Redis クライアントを設定した場合、以下を使用してデータソースを注入することができます。

@Inject RedisDataSource defaultRedisDataSource;
@Inject ReactiveRedisDataSource defaultReactiveRedisDataSource;

名前付きの Redis クライアントを設定した場合、 io.quarkus.redis.RedisClientName 修飾子を使用して、正しいクライアントを選択する必要があります。

@RedisClientName("my-redis") RedisDataSource myRedisDataSource;
@RedisClientName("my-redis") ReactiveRedisDataSource myReactiveRedisDataSource;

ブロッキング バリアントを使用する場合は、以下を使用してデフォルトのタイムアウトを設定できます。

quarkus.redis.timeout=5s
quarkus.redis.my-redis.timeout=5s

デフォルトのタイムアウトは 10 秒に設定されています。

デリゲーションについて

ブロッキングデータソース (io.quarkus.redis.datasource.RedisDataSource) はリアクティブデータソース (io.quarkus.redis.datasource.ReactiveRedisDataSource) の上に実装されています。 ReactiveRedisDataSourceio.vertx.mutiny.redis.Redis API の上に実装されています。

5.1.1. データソースグループ

前述の通り、API はグループに分かれています。

  • bitmap - .bitmap()

  • key (generic) - .key()

  • geo - .geo(memberType)

  • hash - .hash(`valueType)

  • hyperloglog - .hyperloglog(memberType)

  • list - .list(memberType)

  • pubsub - pubsub()

  • set - .set(memberType)

  • sorted-set - .sortedSet(memberType)

  • string - .value(valueType)

  • stream - .stream(`valueType)`

  • transactions - withTransaction

  • json - .json() (サーバー側に RedisJSON モジュールが必要)

  • bloom - .bloom() (サーバー側に RedisBloom モジュールが必要)

  • cuckoo - .cuckoo() (サーバー側に rRedisBloom モジュールが必要で、cuckoo フィルターコマンドも提供されます)

  • count-min - .countmin() (サーバー側に RedisBloom モジュールが必要で、count-min フィルターコマンドも提供されます)

  • top-k - .topk() (サーバー側に RedisBloom モジュールが必要で、top-k フィルターコマンドも提供されます)

  • graph - .graph() (サーバー側に RedisGraph モジュールが必要)。これらのコマンドは experimental とマークされています。また、このモジュールは Redis により end of life と宣言されています。

  • search - .search() (サーバー側に RedisSearch モジュールが必要)

  • auto-suggest - .autosuggest() (サーバー側に RedisSearch モジュールが必要)

  • time-series - .timeseries() (サーバー側に Redis Time Series モジュールが必要)

これらのコマンドは、stable になる前にフィードバックを必要とするため、experimental としてマークされています。

これらのメソッドはそれぞれ、そのグループに関連するコマンドを実行することができるオブジェクトを返します。以下のスニペットは、ハッシュ グループの使い方を示しています。

@ApplicationScoped
public class MyRedisService {

    private static final String MY_KEY = "my-key";

    private final HashCommands<String, String, Person> commands;

    public MyRedisService(RedisDataSource ds) { (1)
        commands = ds.hash(Person.class); (2)
    }

    public void set(String field, Person value) {
        commands.hset(MY_KEY, field, value);  (3)
    }

    public Person get(String field) {
        return commands.hget(MY_KEY, field);  (4)
    }
}
1 コンストラクターに RedisDataSource を注入します。
2 HashCommands オブジェクトを作成します。このオブジェクトには 3 つの型パラメーターがあります: キーの型、フィールドの型、メンバーの型。
3 作成した commands を使用して、フィールド field と値 value を関連付けます。
4 作成した commands を使用して、フィールド field の値を取得します。

5.2. データのシリアライズとデシリアライズ

データソース API は、シリアライズとデシリアライズを自動的に処理します。デフォルトでは、非標準型は JSON にシリアライズされ、JSON からデシリアライズされます。この場合、 quarkus-jackson が使用されます。

5.3. バイナリ

バイナリデータを保存または取得するには、 byte[] を使用します。

5.4. カスタムコーデック

io.quarkus.redis.datasource.codecs.Codec インターフェースを実装する CDI Bean を提供することで、カスタムコーデックを登録できます。

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.redis.datasource.codecs.Codec;

@ApplicationScoped
public class PersonCodec implements Codec {
    @Override
    public boolean canHandle(Type clazz) {
        return clazz.equals(Person.class);
    }

    @Override
    public byte[] encode(Object item) {
        var p = (Person) item;
        return (p.firstName + ";" + p.lastName.toUpperCase()).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public Object decode(byte[] item) {
        var value = new String(item, StandardCharsets.UTF_8);
        var segments = value.split(";");
        return new Person(segments[0], segments[1]);
    }
}

canHandle メソッドは、コーデックが特定の型を扱えるかどうかをチェックするために呼び出されます。encode メソッドで受け取るパラメーターは、その型と一致します。decode メソッドによって返されるオブジェクトも、その型と一致する必要があります。

5.5. 型参照の使用

各グループは、 Class または TypeReference オブジェクトで設定できます。TypeReference は、Java ジェネリクスを扱うときに役立ちます。

@ApplicationScoped
public class MyRedisService {

    private static final String MY_KEY = "my-key";

    private final HashCommands<String, String, List<Person>> commands;

    public MyRedisService(RedisDataSource ds) {
        commands = ds.hash(new TypeReference<List<Person>>(){});
    }

    public void set(String field, List<Person> value) {
        commands.hset(MY_KEY, field, value);
    }

    public List<Person> get(String field) {
        return commands.hget(MY_KEY, field);
    }
}
トランザクションを使用している場合、型参照を使用することはできません。これは既知の制限事項です。

5.6. value グループによるキャッシュ済みおよびバイナリーデータの操作

value グループは Redis 文字列 を操作するために使用されます。したがって、このグループは Java の文字列に限定されず、整数 (カウンターなど) やバイナリーコンテンツ (イメージなど) にも使用できます。

5.6.1. キャッシュされた値の操作

Redis をキャッシュとして使用するには、特定のキーに特定の値を特定の期間格納する setex コマンドを使用します。次のスニペットは、このコマンドを使用して BusinessObject を 1 秒間格納する方法を示しています。

@ApplicationScoped
public static class MyRedisCache {

    private final ValueCommands<String, BusinessObject> commands;

    public MyRedisCache(RedisDataSource ds) {
        commands = ds.value(BusinessObject.class);
    }

    public BusinessObject get(String key) {
        return commands.get(key);
    }

    public void set(String key, BusinessObject bo) {
        commands.setex(key, 1, bo); // Expires after 1 second
    }
}

setnx メソッドは、指定されたキーに値が格納されていない場合にのみ、値を設定するために使用できます。

key グループは、各キーの有効期限と TTL をより細かく制御します。

set メソッドは、動作を変更する SetArgs 引数を受け取ることもできます。

  • ex(seconds) - 指定された有効期限を秒単位で設定します。

  • px(milliseconds) - 指定された有効期限をミリ秒単位で設定します。

  • exat(timestamp-seconds) - キーの有効期限が切れる指定された Unix 時間を秒単位で設定します。

  • pxat(timestamp-milliseconds) - キーの有効期限が切れる指定された Unix 時間をミリ秒単位で設定します。

  • nx() - キーがまだ存在しない場合にのみ設定します。

  • xx() - キーがすでに存在する場合にのみ設定します。

  • keepttl() - キーに関連付けられた TTL (Time To Live) を保持します。

5.6.2. バイナリーデータの格納

Redis の 文字列 は、画像のようなバイナリーデータを格納するために使用できます。この場合、値の型として byte[] を使用します。

@ApplicationScoped
public static class MyBinaryRepository {

    private final ValueCommands<String, byte[]> commands;

    public MyBinaryRepository(RedisDataSource ds) {
        commands = ds.value(byte[].class);
    }

    public byte[] get(String key) {
        byte[] bytes = commands.get(key);
        if (bytes == null) {
            throw new NoSuchElementException("`" + key + "` not found");
        }
        return bytes;
    }

    public void add(String key, byte[] bytes) {
        commands.set(key, bytes);
    }

    public void addIfAbsent(String key, byte[] bytes) {
        commands.setnx(key, bytes);
    }
}

5.6.3. カウンターの格納

以下に示すように、Redis にカウンターを格納できます。

@ApplicationScoped
public static class MyRedisCounter {

    private final ValueCommands<String, Long> commands;

    public MyRedisCounter(RedisDataSource ds) {
        commands = ds.value(Long.class); (1)
    }

    public long get(String key) {
        Long l = commands.get(key);  (2)
        if (l == null) {
            return 0L;
        }
        return l;
    }

    public void incr(String key) {
        commands.incr(key);  (3)
    }

}
1 コマンドを取得します。今回は Long 値を操作します。
2 指定された key に関連付けられたカウンターを取得します。カウンターが格納されていない場合は 0L を返します。
3 値をインクリメントします。キーにカウンターが格納されていない場合、 incr コマンドは 0 を値と見なし (したがって incr は値を 1 に設定します)。

カウンターを操作する際に便利なその他のメソッドには、次のようなものがあります。

  • incrby - 増分値 (正または負) を設定できます。

  • incrbyfloat - 増分値を float/double として設定できます (格納される値は double になります)。

  • set - 必要に応じて初期値を設定します。

  • decr および decrby - 格納された値をデクリメントできます。

5.7. pub/sub との通信

Redis は、メッセージ をチャネルに送信し、それらのメッセージをリッスンすることを可能にします。これらの機能は pubsub グループから利用できます。

次のスニペットは、キャッシュset のたびに Notification を発行する方法と、サブスクライバーがその通知を受信する方法を示しています。

public static final class Notification {
    public String key;
    public BusinessObject bo;

    public Notification() {

    }

    public Notification(String key, BusinessObject bo) {
        this.key = key;
        this.bo = bo;
    }
}

@ApplicationScoped
@Startup // We want to create the bean instance on startup to subscribe to the channel.
public static class MySubscriber implements Consumer<Notification> {
    private final PubSubCommands<Notification> pub;
    private final PubSubCommands.RedisSubscriber subscriber;

    public MySubscriber(RedisDataSource ds) {
        pub = ds.pubsub(Notification.class);
        subscriber = pub.subscribe("notifications", this);
    }

    @Override
    public void accept(Notification notification) {
        // Receive the notification
    }

    @PreDestroy
    public void terminate() {
        subscriber.unsubscribe(); // Unsubscribe from all subscribed channels
    }
}

@ApplicationScoped
public static class MyCache {

    private final ValueCommands<String, BusinessObject> commands;
    private final PubSubCommands<Notification> pub;

    public MyCache(RedisDataSource ds) {
        commands = ds.value(BusinessObject.class);
        pub = ds.pubsub(Notification.class);
    }

    public BusinessObject get(String key) {
        return commands.get(key);
    }

    public void set(String key, BusinessObject bo) {
        commands.set(key, bo);
        pub.publish("notifications", new Notification(key, bo));
    }
}

5.8. Redis トランザクションの使用

Redis トランザクションは、リレーショナルデータベースのトランザクションとは少し異なります。Redis トランザクションは、コマンドをまとめて実行するバッチです。

Redis トランザクションは一連のキーを 監視 することができ、トランザクションの実行中にこれらのキーのいずれかが更新された場合、トランザクションは 破棄 されます。

トランザクション内でキューに入れられたコマンドは、トランザクション全体が実行されるまで実行されません。つまり、トランザクション中に結果を取得することはできません。結果は、トランザクション完了後にアクセスする TransactionResult オブジェクトに蓄積されます。このオブジェクトには、トランザクションが成功したか破棄されたかが含まれており、成功した場合は各コマンドの結果 (コマンドの順序でインデックス付けされます) が含まれます。

トランザクションを開始するには、 withTransaction メソッドを使用します。このメソッドは Consumer<TransactionalRedisDataSource> を受け取ります。これは、コマンドが void (リアクティブバリアントでは Uni<Void>) を返すことを除けば、通常の RedisDataSource と同じ API です。このコンシューマーが戻ると、トランザクションは 実行 されます。

次のスニペットは、2 つの関連する 書き込み を実行するトランザクションを作成する方法を示しています。

@Inject RedisDataSource ds;

// ...

TransactionResult result = ds.withTransaction(tx -> {
        TransactionalHashCommands<String, String, String> hash = tx.hash(String.class);
        hash.hset(KEY, "field-1", "hello");
        hash.hset(KEY, "field-2", "hello");
    });

受け取った tx オブジェクトは、 tx.discard() を使用してトランザクションを 破棄 するためにも使用できます。返された TransactionResult を使用すると、各コマンドの結果を取得できます。

データソースのリアクティブバリアントを使用する場合、渡されるコールバックは Function<ReactiveTransactionalRedisDataSource, Uni<Void>> です。

@Inject ReactiveRedisDataSource ds;

// ...

Uni<TransactionResult> result = ds.withTransaction(tx -> {
        ReactiveTransactionalHashCommands<String, String, String> hash = tx.hash(String.class);
        return hash.hset(KEY, "field-1", "hello")
            .chain(() -> hash.hset(KEY, "field-2", "hello"));
});

トランザクションの実行は キー によって条件付けられます。渡されたキーがトランザクションの実行中に変更された場合、トランザクションは破棄されます。キーは withTransaction メソッドの 2 番目の可変長引数として Strings で渡されます。

TransactionResult result = ds.withTransaction(tx -> {
    TransactionalHashCommands<String, String, String> hash = tx.hash(String.class);
    hash.hset(KEY, "field-1", "hello");
    hash.hset(KEY, "field-2", "hello");
}, KEY);
トランザクション内から pub/sub 機能を使用することはできません。

5.8.1. 楽観的ロックパターンの実装

楽観的ロックを使用するには、トランザクション開始前にコードの実行を許可する withTransaction メソッドのバリアントを使用する必要があります。言い換えれば、次のように実行されます。

WATCH key

// Pre-transaction block
// ...
// Produce a result

MULTI

// In transaction code, receive the result produced by the pre-transaction block.

EXEC

たとえば、フィールドが存在する場合にのみハッシュ内の値を更新する必要がある場合は、次の API を使用します。

OptimisticLockingTransactionResult<Boolean> result = blocking.withTransaction(ds -> {
    // The pre-transaction block:
    HashCommands<String, String, String> hashCommands = ds.hash(String.class);
    return hashCommands.hexists(key, "field"); // Produce a result (boolean in this case)
},
(exists, tx) -> {
    // The transactional block, receives the result and the transactional data source
    if (exists) {
        tx.hash(String.class).hset(key, "field", "new value");
    } else {
        tx.discard();
    }
},
// The watched key
key);

プレトランザクションブロックまたはトランザクションブロックの実行前または実行中に、監視されているキーのいずれかが変更された場合、トランザクションは中止されます。プレトランザクションブロックは、トランザクションブロックが使用できる結果を生成します。この構造が必要なのは、トランザクション内ではコマンドが結果を生成しないためです。結果はトランザクションの実行後にのみ取得できます。

プレトランザクションブロックとトランザクションブロックは、同じ Redis 接続で呼び出されます。したがって、プレトランザクションブロックは渡されたデータソースを使用してコマンドを実行する必要があります。これにより、コマンドはその接続から発行されます。これらのコマンドは、監視されているキーを変更してはなりません。

5.8.2. エラー処理

トランザクションブロックが正常に返された場合 (またはリアクティブAPIの場合にアイテムで完了した場合)、トランザクションが実行されます。この場合、一部のトランザクションコマンドは成功し、一部は失敗する可能性があることに注意してください。これは標準的なRedisの動作です。 TransactionResult.hasErrors() メソッドは、少なくとも1つのコマンドが失敗したかどうかを示します。 TransactionResult 内の失敗したコマンドの結果は、Throwable として表されます。トランザクションブロックが例外をスローした場合 (またはリアクティブAPIの場合に失敗で完了した場合)、トランザクションは自動的に破棄され、例外が再スローされます (または、結果として得られる Uni はリアクティブAPIの場合に同じ失敗で完了します)。

楽観的ロックAPIの場合、プレトランザクションブロックが正常に返された場合 (またはリアクティブAPIの場合にアイテムで完了した場合)、トランザクションが開始され、実行はトランザクションブロックに進みます。プレトランザクションブロックが例外をスローした場合 (またはリアクティブAPIの場合に失敗で完了した場合)、監視されているすべてのキーは自動的に UNWATCH され、例外が再スローされます (または、結果として得られる Uni はリアクティブAPIの場合に同じ失敗で完了します)。この場合、トランザクションは開始されず、トランザクションブロックも実行されません。

5.8.3. Redis Cluster のトランザクション

クラスターモードでは、トランザクションコマンド ( MULTIEXECDISCARDWATCHUNWATCH ) は特別に扱われます。

デフォルトでは、クラスターでのトランザクションは無効になっており、トランザクションコマンドはすぐに失敗します。

ただし、 quarkus.redis.cluster-transactionssingle-node に設定することで、単一ノードトランザクションを有効にすることは可能です。この設定はクラスターモードでのみ意味があり、それ以外の場合は無視されることに注意してください。

このモードでは、 MULTI コマンドはキューに入れられ、次のコマンドが実行されたときにのみ発行されます。この次のコマンドは、接続をRedisクラスターの対応するノードにバインドします (したがって、キーを持つべきであり、そうでない場合はターゲットノードはランダムになります)。後続のすべてのコマンドはそのノードをターゲットとします。後続のコマンドの一部に別のノードに属するキーがある場合、コマンドはサーバー側で失敗します。 WATCHMULTI の前に使用された場合、そのキーによって接続がバインドされるノードが決まり、後続の MULTI はキューに入れられません。 WATCH キーが複数のノードに属している場合、コマンドはクライアント側で失敗します。

5.9. カスタムコマンドの実行

カスタムコマンドやAPIでサポートされていないコマンドを実行するには、以下の方法を使用します。

@Inject ReactiveRedisDataSource ds;

// ...

Response response = ds.execute("my-command", param1, param2, param3);

execute メソッドは Redis にコマンドを送信し、 Response を取得します。コマンド名は最初のパラメーターとして渡されます。コマンドには、任意の数の String パラメーターを追加することができます。結果は Response オブジェクトにラップされます。

リアクティブバリアントは Uni<Response> を返します。

また、トランザクション内でカスタムコマンドを実行することも可能です。

6. Redisにデータをプリロードする

起動時に、RedisクライアントはRedisデータベースにデータをプリロードするように設定することができます。

6.1. ロードスクリプトの設定

使用する ロードスクリプト を指定します:

quarkus.redis.load-script=import.redis # import.redis is the default in dev mode, no-file is the default in production mode
quarkus.redis.my-redis.load-script=actors.redis, movies.redis
load-script はビルド時のプロパティであり、実行時にオーバーライドすることはできません。

各クライアントは異なるスクリプトを持つことができ、スクリプトのリストを持つこともできることに注意してください。リストの場合、データはリストの順番でインポートされます (たとえば、 my-redis クライアントの場合、最初に actors.redis 、次に movies.redis )。

6.2. ロードスクリプトの作成

.redis ファイルは、 1行に1コマンド の形式をとっています:

# Line starting with # and -- are ignored, as well as empty lines

-- One command per line:
HSET foo field1 abc field2 123

-- Parameters with spaces must be wrapped into single or double quotes
HSET bar field1 "abc def" field2 '123 456 '

-- Parameters with double quotes must be wrapped into single quotes and the opposite
SET key1 'A value using "double-quotes"'
SET key2 "A value using 'single-quotes'"

Quarkusは、1つのファイルからすべてのコマンドを一括して送信します。読み込み処理はエラーがあると失敗しますが、前の命令が実行されている可能性があります。それを避けるために、コマンドをRedis トランザクション にラップすることができます:

-- Run inside a transaction
MULTI
SET key value
SET space:key 'another value'
INCR counter
EXEC

6.3. プリロードの設定

アプリケーションの起動時にデータが読み込まれます。デフォルトでは、インポートする前にデータベース全体をドロップします。これは quarkus.redis.flush-before-load=false を使用して防ぐことができます。

また、インポート処理は、データベースが空 (キーなし) の場合のみ実行されます。 quarkus.redis.load-only-if-empty=false を使用すれば、データがあっても強制的にインポートすることができます。

6.4. プリロード時の開発/テストと実稼働の区別

上記のように、開発モードとテストモードでは、Quarkusは src/main/resources/import.redis を探してデータをインポートしようとします。この動作は prod モードでは無効になっており、実稼働環境でもインポートしたい場合は、以下を追加します:

%prod.quarkus.redis.load-script=import.redis

prod モードでインポートする前に、 quarkus.redis.flush-before-load を適切に設定してください。

開発モードでは、 .redis ロードスクリプトの内容を再読み込みするため、 %dev.quarkus.vertx.caching=false を追加する必要があります。

7. Vert.x redisクライアントの使用

高レベルのAPIに加えて、コードでVertx Redisクライアントを直接使用することができます。Vert.x Redisクライアントのドキュメントは Vert.x Web サイト で公開されています。

8. プログラムでRedisホストを設定

RedisHostsProvider はプログラムによってRedisホストを提供します。これにより、他のソースから取得したRedis接続パスワードのようなプロパティーを設定することができます。

これは、application.properties に機密データを格納する必要がなくなるため便利です。

@ApplicationScoped
@Identifier("hosts-provider") // the name of the host provider
public class ExampleRedisHostProvider implements RedisHostsProvider {
    @Override
    public Set<URI> getHosts() {
        // do stuff to get the host
        String host = "redis://localhost:6379/3";
        return Collections.singleton(URI.create(host));
    }
}

以下に示すように、ホストプロバイダーを使用してredisクライアントを設定することができます。

quarkus.redis.hosts-provider-name=hosts-provider

9. プログラムによる Redis オプションのカスタマイズ

Redisクライアントのオプションをカスタマイズするために、 io.quarkus.redis.client.RedisOptionsCustomizer インターフェイスを実装したBeanを公開することができます。このBeanは、設定された各Redisクライアントに対して呼び出されます。

@ApplicationScoped
public static class MyExampleCustomizer implements RedisOptionsCustomizer {

    @Override
    public void customize(String clientName, RedisOptions options) {
        if (clientName.equalsIgnoreCase("my-redis")
                || clientName.equalsIgnoreCase(RedisConfig.DEFAULT_CLIENT_NAME)) {
            // modify the given options
        } else {
            throw new IllegalStateException("Unknown client name: " + clientName);
        }
    }
}

9.1. Redis Dev Servicesの使用

Redis Dev Service を参照してください。

10. Redisのオブザーバビリティの設定

10.1. ヘルスチェックの有効化

quarkus-smallrye-health エクステンションを使用している場合、 quarkus-redis はRedisサーバーへの接続を検証するためのreadiness probeを自動的に追加します。

そのため、アプリケーションの /q/health/ready エンドポイントにアクセスすると、接続の検証状況に関する情報が得られます。

この動作は、 application.propertiesquarkus.redis.health.enabled プロパティーを false に設定することで無効にできます。

10.2. メトリクスの有効化

Redisクライアントのメトリクスは、アプリケーションが quarkus-micrometer エクステンションも使用している場合に自動的に有効になります。Micrometerは、アプリケーションによって実装されるすべてのRedisクライアントのメトリクスを収集します。

例として、メトリクスをPrometheusにエクスポートした場合、次のような結果が得られます:

# HELP redis_commands_duration_seconds The duration of the operations (commands of batches
# TYPE redis_commands_duration_seconds summary
redis_commands_duration_seconds_count{client_name="<default>",} 3.0
redis_commands_duration_seconds_sum{client_name="<default>",} 0.047500042
# HELP redis_commands_duration_seconds_max The duration of the operations (commands of batches
# TYPE redis_commands_duration_seconds_max gauge
redis_commands_duration_seconds_max{client_name="<default>",} 0.033273167
# HELP redis_pool_active The number of resources from the pool currently used
# TYPE redis_pool_active gauge
redis_pool_active{pool_name="<default>",pool_type="redis",} 0.0
# HELP redis_pool_ratio Pool usage ratio
# TYPE redis_pool_ratio gauge
redis_pool_ratio{pool_name="<default>",pool_type="redis",} 0.0
# HELP redis_pool_queue_size Number of pending elements in the waiting queue
# TYPE redis_pool_queue_size gauge
redis_pool_queue_size{pool_name="<default>",pool_type="redis",} 0.0
# HELP redis_commands_failure_total The number of operations (commands or batches) that have been failed
# TYPE redis_commands_failure_total counter
redis_commands_failure_total{client_name="<default>",} 0.0
# HELP redis_commands_success_total The number of operations (commands or batches) that have been executed successfully
# TYPE redis_commands_success_total counter
redis_commands_success_total{client_name="<default>",} 3.0
# HELP redis_pool_idle The number of resources from the pool currently used
# TYPE redis_pool_idle gauge
redis_pool_idle{pool_name="<default>",pool_type="redis",} 6.0
# HELP redis_pool_completed_total Number of times resources from the pool have been acquired
# TYPE redis_pool_completed_total counter
redis_pool_completed_total{pool_name="<default>",pool_type="redis",} 3.0
# HELP redis_commands_count_total The number of operations (commands or batches) executed
# TYPE redis_commands_count_total counter
redis_commands_count_total{client_name="<default>",} 3.0
# HELP redis_pool_usage_seconds Time spent using resources from the pool
# TYPE redis_pool_usage_seconds summary
redis_pool_usage_seconds_count{pool_name="<default>",pool_type="redis",} 3.0
redis_pool_usage_seconds_sum{pool_name="<default>",pool_type="redis",} 0.024381375
# HELP redis_pool_usage_seconds_max Time spent using resources from the pool
# TYPE redis_pool_usage_seconds_max gauge
redis_pool_usage_seconds_max{pool_name="<default>",pool_type="redis",} 0.010671542
# HELP redis_pool_queue_delay_seconds Time spent in the waiting queue before being processed
# TYPE redis_pool_queue_delay_seconds summary
redis_pool_queue_delay_seconds_count{pool_name="<default>",pool_type="redis",} 3.0
redis_pool_queue_delay_seconds_sum{pool_name="<default>",pool_type="redis",} 0.022341249
# HELP redis_pool_queue_delay_seconds_max Time spent in the waiting queue before being processed
# TYPE redis_pool_queue_delay_seconds_max gauge
redis_pool_queue_delay_seconds_max{pool_name="<default>",pool_type="redis",} 0.021926083

Redisクライアント名は、 タグ で確認できます。

メトリクスには、Redis接続プールのメトリクス ( redis_pool_* ) と、コマンド実行に関するメトリクス ( redis_commands_* ) (コマンド数、成功、失敗、継続時間など) の両方が含まれています。

10.3. メトリクスの無効化

quarkus-micrometer を使用しているときに Redis クライアントメトリクスを無効にするには、アプリケーション設定に以下のプロパティーを追加します:

quarkus.micrometer.binder.redis.enabled=false

11. 設定リファレンス

ビルド時に固定される設定プロパティー - 他のすべての設定プロパティーは実行時にオーバーライド可能

Configuration property

タイプ

デフォルト

Whether a health check is published in case the smallrye-health extension is present.

Environment variable: QUARKUS_REDIS_HEALTH_ENABLED

Show more

ブーリアン

true

quarkus.redis."redis-client-name".load-script

A list of files allowing to pre-load data into the Redis server. The file is formatted as follows:

  • One instruction per line

  • Each instruction is a Redis command and its parameter such as HSET foo field value

  • Parameters can be wrapped into double-quotes if they include spaces

  • Parameters can be wrapped into single-quote if they include spaces

  • Parameters including double-quotes must be wrapped into single-quotes

Environment variable: QUARKUS_REDIS_LOAD_SCRIPT

Show more

list of string

import.redis in DEV, TEST ; no-file otherwise

quarkus.redis."redis-client-name".flush-before-load

When using redisLoadScript, indicates if the Redis database must be flushed (erased) before importing.

Environment variable: QUARKUS_REDIS_FLUSH_BEFORE_LOAD

Show more

ブーリアン

true

quarkus.redis."redis-client-name".load-only-if-empty

When using redisLoadScript, indicates if the import should only happen if the database is empty (no keys).

Environment variable: QUARKUS_REDIS_LOAD_ONLY_IF_EMPTY

Show more

ブーリアン

true

quarkus.redis."redis-client-name".active

Whether this Redis Client should be active at runtime.

Environment variable: QUARKUS_REDIS_ACTIVE

Show more

ブーリアン

true

quarkus.redis."redis-client-name".hosts

The Redis hosts to use while connecting to the Redis server. Only the cluster and sentinel modes will consider more than 1 element.

The URI provided uses the following schema redis://[username:password@][host][:port][/database] Use quarkus.redis.hosts-provider-name to provide the hosts programmatically.

Environment variable: QUARKUS_REDIS_HOSTS

Show more

list of URI

quarkus.redis."redis-client-name".hosts-provider-name

The hosts provider bean name.

It is the &#64;Named value of the hosts provider bean. It is used to discriminate if multiple io.quarkus.redis.client.RedisHostsProvider beans are available.

Used when quarkus.redis.hosts is not set.

Environment variable: QUARKUS_REDIS_HOSTS_PROVIDER_NAME

Show more

string

quarkus.redis."redis-client-name".timeout

The maximum delay to wait before a blocking command to Redis server times out

Environment variable: QUARKUS_REDIS_TIMEOUT

Show more

Duration 

10S

quarkus.redis."redis-client-name".client-type

The Redis client type. Accepted values are: STANDALONE (default), CLUSTER, REPLICATION, SENTINEL.

Environment variable: QUARKUS_REDIS_CLIENT_TYPE

Show more

standalone, sentinel, cluster, replication

standalone

quarkus.redis."redis-client-name".master-name

The master name (only considered in the Sentinel mode).

Environment variable: QUARKUS_REDIS_MASTER_NAME

Show more

string

mymaster

quarkus.redis."redis-client-name".role

The role name (only considered in the Sentinel mode). Accepted values are: MASTER, REPLICA, SENTINEL.

Environment variable: QUARKUS_REDIS_ROLE

Show more

master, replica, sentinel

master

quarkus.redis."redis-client-name".replicas

Whether to use replicas nodes (only considered in Cluster mode and Replication mode). Accepted values are: ALWAYS, NEVER, SHARE.

Environment variable: QUARKUS_REDIS_REPLICAS

Show more

never, share, always

never

quarkus.redis."redis-client-name".password

The default password for Redis connections.

If not set, it will try to extract the value from the hosts.

Environment variable: QUARKUS_REDIS_PASSWORD

Show more

string

quarkus.redis."redis-client-name".max-pool-size

The maximum size of the connection pool.

Environment variable: QUARKUS_REDIS_MAX_POOL_SIZE

Show more

int

6

quarkus.redis."redis-client-name".max-pool-waiting

The maximum waiting requests for a connection from the pool.

Environment variable: QUARKUS_REDIS_MAX_POOL_WAITING

Show more

int

24

quarkus.redis."redis-client-name".pool-cleaner-interval

The duration indicating how often should the connection pool cleaner execute.

Environment variable: QUARKUS_REDIS_POOL_CLEANER_INTERVAL

Show more

Duration 

30s

quarkus.redis."redis-client-name".pool-recycle-timeout

The timeout for unused connection recycling.

Environment variable: QUARKUS_REDIS_POOL_RECYCLE_TIMEOUT

Show more

Duration 

3M

quarkus.redis."redis-client-name".max-waiting-handlers

Sets how many handlers is the client willing to queue.

The client will always work on pipeline mode, this means that messages can start queueing. Using this configuration option, you can control how much backlog you’re willing to accept.

Environment variable: QUARKUS_REDIS_MAX_WAITING_HANDLERS

Show more

int

2048

quarkus.redis."redis-client-name".max-nested-arrays

Tune how much nested arrays are allowed on a Redis response. This affects the parser performance.

Environment variable: QUARKUS_REDIS_MAX_NESTED_ARRAYS

Show more

int

32

quarkus.redis."redis-client-name".reconnect-attempts

The number of reconnection attempts when a pooled connection cannot be established on first try.

Environment variable: QUARKUS_REDIS_RECONNECT_ATTEMPTS

Show more

int

0

quarkus.redis."redis-client-name".reconnect-interval

The interval between reconnection attempts when a pooled connection cannot be established on first try.

Environment variable: QUARKUS_REDIS_RECONNECT_INTERVAL

Show more

Duration 

1S

quarkus.redis."redis-client-name".protocol-negotiation

Should the client perform RESP protocol negotiation during the connection handshake.

Environment variable: QUARKUS_REDIS_PROTOCOL_NEGOTIATION

Show more

ブーリアン

true

quarkus.redis."redis-client-name".preferred-protocol-version

The preferred protocol version to be used during protocol negotiation. When not set, defaults to RESP 3. When protocol negotiation is disabled, this setting has no effect.

Environment variable: QUARKUS_REDIS_PREFERRED_PROTOCOL_VERSION

Show more

resp2, resp3

resp3

quarkus.redis."redis-client-name".topology-cache-ttl

The TTL of the topology cache. A topology cache is used by a clustered Redis client and a sentinel Redis client to prevent constantly sending topology discovery commands (CLUSTER SLOTS or SENTINEL …​).

This setting is only meaningful in case of a clustered Redis client and a sentinel Redis client and has no effect otherwise.

Environment variable: QUARKUS_REDIS_TOPOLOGY_CACHE_TTL

Show more

Duration 

1S

quarkus.redis."redis-client-name".auto-failover

Whether automatic failover is enabled. This only makes sense for sentinel clients with role of MASTER and is ignored otherwise.

If enabled, the sentinel client will additionally create a connection to one sentinel node and watch for failover events. When new master is elected, all connections to the old master are automatically closed and new connections to the new master are created. Automatic failover makes sense for connections executing regular commands, but not for connections used to subscribe to Redis pub/sub channels.

Note that there is a brief period of time between the old master failing and the new master being elected when the existing connections will temporarily fail all operations. After the new master is elected, the connections will automatically fail over and start working again.

Environment variable: QUARKUS_REDIS_AUTO_FAILOVER

Show more

ブーリアン

false

quarkus.redis."redis-client-name".topology

How the Redis topology is obtained. By default, the topology is discovered automatically. This is the only mode for the clustered and sentinel client. For replication client, topology may be set statically.

In case of a static topology for replication Redis client, the first node in the list is considered a master and the remaining nodes in the list are considered replicas.

Environment variable: QUARKUS_REDIS_TOPOLOGY

Show more

discover, static

discover

quarkus.redis."redis-client-name".cluster-transactions

How transactions are handled in a cluster. This only makes sense for cluster clients and is ignored otherwise.

By default, transactions in cluster are disabled and transaction commands fail.

When set to single-node, Redis transactions are supported in the cluster, but only when they target a single node. The MULTI command is queued and is only issued when the next command is executed. This next command binds the connection to the corresponding node of the Redis cluster (so it should have keys, otherwise the target node is random). All subsequent commands are targeted to that node. If some of the subsequent commands have a key that belongs to another node, the command will fail on the server side. If WATCH is used before MULTI, its key(s) determine to which node the connection is bound and the subsequent MULTI is not queued. If WATCH keys belong to multiple nodes, the command fails on the client side.

Environment variable: QUARKUS_REDIS_CLUSTER_TRANSACTIONS

Show more

disabled, single-node

disabled

quarkus.redis."redis-client-name".client-name

The client name used to identify the connection.

If the RedisClientConfig#configureClientName() is enabled, and this property is not set it will attempt to extract the value from the RedisClientName#value() annotation.

If the RedisClientConfig#configureClientName() is enabled, both this property and the RedisClientName#value() must adhere to the pattern '[a-zA-Z0-9\\-_.~]*'; if not, this may result in an incorrect client name after URI encoding.

Environment variable: QUARKUS_REDIS_CLIENT_NAME

Show more

string

quarkus.redis."redis-client-name".configure-client-name

Whether it should set the client name while connecting with Redis.

This is necessary because Redis only accepts client=my-client-name query parameter in version 6+.

This property can be used with RedisClientConfig#clientName() configuration.

Environment variable: QUARKUS_REDIS_CONFIGURE_CLIENT_NAME

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls-configuration-name

The name of the TLS configuration to use.

If a name is configured, it uses the configuration from quarkus.tls.<name>.* If a name is configured, but no TLS configuration is found with that name then an error will be thrown.

If no TLS configuration name is set then, quarkus.redis.$client-name.tls will be used.

The default TLS configuration is not used by default.

Environment variable: QUARKUS_REDIS_TLS_CONFIGURATION_NAME

Show more

string

quarkus.redis."redis-client-name".hash-slot-cache-ttl

This property is deprecated since 3.30: use quarkus.redis.topology-cache-ttl.

The TTL of the topology cache. A topology cache is used by a clustered Redis client and a sentinel Redis client to prevent constantly sending topology discovery commands (CLUSTER SLOTS or SENTINEL …​).

This setting is only meaningful in case of a clustered Redis client and a sentinel Redis client and has no effect otherwise.

Environment variable: QUARKUS_REDIS_HASH_SLOT_CACHE_TTL

Show more

Duration 

1S

Dev Services allows Quarkus to automatically start Redis in dev and test mode

タイプ

デフォルト

quarkus.redis."redis-client-name".devservices.enabled

If DevServices has been explicitly enabled or disabled. DevServices is generally enabled by default, unless there is an existing configuration present.

When DevServices is enabled Quarkus will attempt to automatically configure and start a database when running in Dev or Test mode and when Docker is running.

Environment variable: QUARKUS_REDIS_DEVSERVICES_ENABLED

Show more

ブーリアン

true

quarkus.redis."redis-client-name".devservices.image-name

The container image name to use, for container based DevServices providers. If you want to use Redis Stack modules (bloom, graph, search…​), use: redis/redis-stack:latest.

Environment variable: QUARKUS_REDIS_DEVSERVICES_IMAGE_NAME

Show more

string

docker.io/library/redis:7

quarkus.redis."redis-client-name".devservices.port

Optional fixed port the dev service will listen to.

If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_REDIS_DEVSERVICES_PORT

Show more

int

quarkus.redis."redis-client-name".devservices.shared

Indicates if the Redis server managed by Quarkus Dev Services is shared. When shared, Quarkus looks for running containers using label-based service discovery. If a matching container is found, it is used, and so a second one is not started. Otherwise, Dev Services for Redis starts a new container.

The discovery uses the quarkus-dev-service-redis label. The value is configured using the service-name property.

Container sharing is only used in dev mode.

Environment variable: QUARKUS_REDIS_DEVSERVICES_SHARED

Show more

ブーリアン

true

quarkus.redis."redis-client-name".devservices.service-name

The value of the quarkus-dev-service-redis label attached to the started container. This property is used when shared is set to true. In this case, before starting a container, Dev Services for Redis looks for a container with the quarkus-dev-service-redis label set to the configured value. If found, it will use this container instead of starting a new one. Otherwise, it starts a new container with the quarkus-dev-service-redis label set to the specified value.

This property is used when you need multiple shared Redis servers.

Environment variable: QUARKUS_REDIS_DEVSERVICES_SERVICE_NAME

Show more

string

redis

quarkus.redis."redis-client-name".devservices.container-env."environment-variable-name"

Environment variables that are passed to the container.

Environment variable: QUARKUS_REDIS_DEVSERVICES_CONTAINER_ENV__ENVIRONMENT_VARIABLE_NAME_

Show more

Map<String,String>

TCP config

タイプ

デフォルト

quarkus.redis."redis-client-name".tcp.alpn

Set the ALPN usage.

Environment variable: QUARKUS_REDIS_TCP_ALPN

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.application-layer-protocols

Sets the list of application-layer protocols to provide to the server during the Application-Layer Protocol Negotiation.

Environment variable: QUARKUS_REDIS_TCP_APPLICATION_LAYER_PROTOCOLS

Show more

list of string

quarkus.redis."redis-client-name".tcp.secure-transport-protocols

Sets the list of enabled SSL/TLS protocols.

Environment variable: QUARKUS_REDIS_TCP_SECURE_TRANSPORT_PROTOCOLS

Show more

list of string

quarkus.redis."redis-client-name".tcp.idle-timeout

Set the idle timeout.

Environment variable: QUARKUS_REDIS_TCP_IDLE_TIMEOUT

Show more

Duration 

quarkus.redis."redis-client-name".tcp.connection-timeout

Set the connect timeout.

Environment variable: QUARKUS_REDIS_TCP_CONNECTION_TIMEOUT

Show more

Duration 

quarkus.redis."redis-client-name".tcp.proxy-configuration-name

The name of the proxy configuration to use.

If quarkus.redis.tcp.proxy-options.host is set, the quarkus.redis.tcp.proxy-options.* (and quarkus.redis.tcp.non-proxy-hosts) configuration is used and the quarkus.proxy.* configuration is ignored.

Otherwise, if not set and the default proxy configuration is configured (quarkus.proxy.*), it is used. If set to none, no proxy configuration is used. If set to some other value, the configuration from quarkus.proxy.<name>.* is used. If set but no proxy configuration with that name is found, an exception is thrown at runtime.

Environment variable: QUARKUS_REDIS_TCP_PROXY_CONFIGURATION_NAME

Show more

string

quarkus.redis."redis-client-name".tcp.read-idle-timeout

Set the read idle timeout.

Environment variable: QUARKUS_REDIS_TCP_READ_IDLE_TIMEOUT

Show more

Duration 

quarkus.redis."redis-client-name".tcp.receive-buffer-size

Set the TCP receive buffer size.

Environment variable: QUARKUS_REDIS_TCP_RECEIVE_BUFFER_SIZE

Show more

int

quarkus.redis."redis-client-name".tcp.reconnect-attempts

Set the value of reconnect attempts.

Environment variable: QUARKUS_REDIS_TCP_RECONNECT_ATTEMPTS

Show more

int

quarkus.redis."redis-client-name".tcp.reconnect-interval

Set the reconnect interval.

Environment variable: QUARKUS_REDIS_TCP_RECONNECT_INTERVAL

Show more

Duration 

quarkus.redis."redis-client-name".tcp.reuse-address

Whether to reuse the address.

Environment variable: QUARKUS_REDIS_TCP_REUSE_ADDRESS

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.reuse-port

Whether to reuse the port.

Environment variable: QUARKUS_REDIS_TCP_REUSE_PORT

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.send-buffer-size

Set the TCP send buffer size.

Environment variable: QUARKUS_REDIS_TCP_SEND_BUFFER_SIZE

Show more

int

quarkus.redis."redis-client-name".tcp.so-linger

Set the SO_linger keep alive duration.

Environment variable: QUARKUS_REDIS_TCP_SO_LINGER

Show more

Duration 

quarkus.redis."redis-client-name".tcp.cork

Enable the TCP_CORK option - only with linux native transport.

Environment variable: QUARKUS_REDIS_TCP_CORK

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.fast-open

Enable the TCP_FASTOPEN option - only with linux native transport.

Environment variable: QUARKUS_REDIS_TCP_FAST_OPEN

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.keep-alive

Set whether keep alive is enabled

Environment variable: QUARKUS_REDIS_TCP_KEEP_ALIVE

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.no-delay

Set whether no delay is enabled

Environment variable: QUARKUS_REDIS_TCP_NO_DELAY

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.quick-ack

Enable the TCP_QUICKACK option - only with linux native transport.

Environment variable: QUARKUS_REDIS_TCP_QUICK_ACK

Show more

ブーリアン

quarkus.redis."redis-client-name".tcp.traffic-class

Set the value of traffic class.

Environment variable: QUARKUS_REDIS_TCP_TRAFFIC_CLASS

Show more

int

quarkus.redis."redis-client-name".tcp.write-idle-timeout

Set the write idle timeout.

Environment variable: QUARKUS_REDIS_TCP_WRITE_IDLE_TIMEOUT

Show more

Duration 

quarkus.redis."redis-client-name".tcp.local-address

Set the local interface to bind for network connections. When the local address is null, it will pick any local address, the default local address is null.

Environment variable: QUARKUS_REDIS_TCP_LOCAL_ADDRESS

Show more

string

SSL/TLS config

タイプ

デフォルト

quarkus.redis."redis-client-name".tls.enabled

Whether SSL/TLS is enabled.

Environment variable: QUARKUS_REDIS_TLS_ENABLED

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.trust-all

Enable trusting all certificates. Disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_ALL

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.trust-certificate-pem

PEM Trust config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PEM

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.trust-certificate-pem.certs

Comma-separated list of the trust certificate files (Pem format).

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PEM_CERTS

Show more

list of string

quarkus.redis."redis-client-name".tls.trust-certificate-jks

JKS config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_JKS

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.trust-certificate-jks.path

Path of the key file (JKS format).

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_JKS_PATH

Show more

string

quarkus.redis."redis-client-name".tls.trust-certificate-jks.password

Password of the key file.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_JKS_PASSWORD

Show more

string

quarkus.redis."redis-client-name".tls.trust-certificate-pfx

PFX config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PFX

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.trust-certificate-pfx.path

Path to the key file (PFX format).

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PFX_PATH

Show more

string

quarkus.redis."redis-client-name".tls.trust-certificate-pfx.password

Password of the key.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PFX_PASSWORD

Show more

string

quarkus.redis."redis-client-name".tls.key-certificate-pem

PEM Key/cert config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PEM

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.key-certificate-pem.keys

Comma-separated list of the path to the key files (Pem format).

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PEM_KEYS

Show more

list of string

quarkus.redis."redis-client-name".tls.key-certificate-pem.certs

Comma-separated list of the path to the certificate files (Pem format).

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PEM_CERTS

Show more

list of string

quarkus.redis."redis-client-name".tls.key-certificate-jks

JKS config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_JKS

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.key-certificate-jks.path

Path of the key file (JKS format).

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_JKS_PATH

Show more

string

quarkus.redis."redis-client-name".tls.key-certificate-jks.password

Password of the key file.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_JKS_PASSWORD

Show more

string

quarkus.redis."redis-client-name".tls.key-certificate-pfx

PFX config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PFX

Show more

ブーリアン

false

quarkus.redis."redis-client-name".tls.key-certificate-pfx.path

Path to the key file (PFX format).

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PFX_PATH

Show more

string

quarkus.redis."redis-client-name".tls.key-certificate-pfx.password

Password of the key.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PFX_PASSWORD

Show more

string

quarkus.redis."redis-client-name".tls.hostname-verification-algorithm

The hostname verification algorithm to use in case the server’s identity should be checked. Should be HTTPS, LDAPS or NONE (default).

If set to NONE, it does not verify the hostname.

Environment variable: QUARKUS_REDIS_TLS_HOSTNAME_VERIFICATION_ALGORITHM

Show more

string

NONE

期間フォーマットについて

期間の値を書くには、標準の java.time.Duration フォーマットを使います。 詳細は Duration#parse() Java API documentation を参照してください。

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

関連コンテンツ