The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

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

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. Inject the default and named clients

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

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

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

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

@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 アノテーションを省略することができます。

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 を使用する場合、複数の ホスト 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

The host URLs here must be the sentinel servers. The client will obtain the URLs of actual Redis servers (master or replicas, depending on role) from one of the sentinels, using the master-name as an identifier of the "master set".

Note that you practically never want to configure quarkus.redis.role=sentinel. This setting means that the Redis client will execute commands directly on one of the sentinel servers, instead of an actual Redis server guarded by the sentinels.

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"

The host URLs here must be some of the cluster members. Not all cluster members need to be configured, as the client will obtain a full cluster topology from one of the known servers. However, it is advisable to configure at least 2 or 3 nodes, not just 1.

By default, all commands are sent to a master node (if the command has a key, it is the master node of the shard that owns the key, otherwise it is a random master node). It is possible to configure the Redis client to send read-only commands (queries) to replica nodes. Set the quarkus.redis.replicas configuration property to:

  • never: never use replica nodes, always send queries to master nodes (this is the default)

  • always: always use replica nodes (if there’s more than one replica in the shard, it is selected randomly), never send queries to master nodes

  • share: use master and replica nodes to execute queries (the specific node for each query is selected randomly)

Note that replication in Redis is asynchronous, so replica nodes may be lagging behind their master nodes.

4.4. Use the Replication Mode

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

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

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

By default, all commands are sent to the master node. It is possible to configure the Redis client to send read-only commands (queries) to replica nodes. Set the quarkus.redis.replicas configuration property to:

  • never: never use replica nodes, always send queries to the master node (this is the default)

  • always: always use replica nodes (if there’s more than one replica, it is selected randomly), never send queries to the master node

  • share: use master and replica nodes to execute queries (the specific node for each query is selected randomly)

Note that replication in Redis is asynchronous, so replica nodes may be lagging behind the master node.

4.5. Redisクラウドに接続

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 プロパティを設定

  2. URLが rediss:// (2つの s )で始まるようにする

The default hostname verifier is set to NONE, meaning it does not verify the host name. You can change this behavior by setting the quarkus.redis.tls.hostname-verification-algorithm property, to HTTPS for example.

4.7. 認証の設定

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

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

4.8. Connection pooling

Connections to Redis are always pooled. By default, maximum number of connections in the pool is 6. This can be configured using quarkus.redis.max-pool-size.

When the connection pool is depleted, attempts to obtain a connection are put into a queue. By default, maximum number of attempts waiting in the queue to obtain a Redis connection is 24. This can be configured using quarkus.redis.max-pool-waiting.

Executing certain commands modifies the server-side state and the behavior of the connection. Such connections cannot be reused and when closed, they are not put back into the pool; instead, they are truly closed. The commands that cause this behavior are:

  • subscription commands (SUBSCRIBE, UNSUBSCRIBE etc.)

  • 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 モジュールが必要)。 これらのコマンドは実験的なものです。 また、このモジュールは Redis によって 終了 が 宣言されています。

  • 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. Use type reference

Each group can be configured with Class, or with TypeReference objects. TypeReference are useful when dealing with Java generics:

@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);
    }
}
You cannot use type references when using transaction. This is a known limitation.

5.6. Manipulate cached and binary data with the value group

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(): キーに関連付けられた有効期限を保持します。

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.6.4. 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.6.5. 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 パラメーターとして String として渡されます。

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.6.6. 楽観的ロックパターンの実装

楽観ロックを使用するには、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();
        }
 },
  key); // The watched key

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

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

プレトランザクションブロックが例外をスローした場合 (またはリアクティブ API を使用している場合はエラーを生成した場合)、トランザクションは中断されます。

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

カスタムコマンドや 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 はビルド時のプロパティであり、実行時にオーバーライドすることはできません。

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

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

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

6.4. Distinguish dev/test vs. prod when pre-loading

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

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

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

devモードでは、 .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 ヘルスチェックを自動的に追加します。

そのため、アプリケーションの /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

デフォルト

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

string

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

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

Environment variable: QUARKUS_REDIS_FLUSH_BEFORE_LOAD

Show more

boolean

true

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

boolean

true

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

Environment variable: QUARKUS_REDIS_HEALTH_ENABLED

Show more

boolean

true

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

boolean

true

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

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

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

boolean

true

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

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

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

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

Environment variable: QUARKUS_REDIS_TIMEOUT

Show more

Duration

10S

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

The master name (only considered in HA mode).

Environment variable: QUARKUS_REDIS_MASTER_NAME

Show more

string

mymaster

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

Environment variable: QUARKUS_REDIS_ROLE

Show more

master, replica, sentinel

master

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

Environment variable: QUARKUS_REDIS_REPLICAS

Show more

never, share, always

never

The default password for cluster/sentinel connections.

If not set it will try to extract the value from the current default #hosts.

Environment variable: QUARKUS_REDIS_PASSWORD

Show more

string

The maximum size of the connection pool. When working with cluster or sentinel.

This value should be at least the total number of cluster member (or number of sentinels + 1)

Environment variable: QUARKUS_REDIS_MAX_POOL_SIZE

Show more

int

6

The maximum waiting requests for a connection from the pool.

Environment variable: QUARKUS_REDIS_MAX_POOL_WAITING

Show more

int

24

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

Environment variable: QUARKUS_REDIS_POOL_CLEANER_INTERVAL

Show more

Duration

The timeout for a connection recycling.

Environment variable: QUARKUS_REDIS_POOL_RECYCLE_TIMEOUT

Show more

Duration

15S

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

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

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

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

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

Environment variable: QUARKUS_REDIS_PROTOCOL_NEGOTIATION

Show more

boolean

true

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

The TTL of the hash slot cache. A hash slot cache is used by the clustered Redis client to prevent constantly sending CLUSTER SLOTS commands to the first statically configured cluster node.

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

Environment variable: QUARKUS_REDIS_HASH_SLOT_CACHE_TTL

Show more

Duration

1S

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__REDIS_CLIENT_NAME__LOAD_SCRIPT

Show more

string

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

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__FLUSH_BEFORE_LOAD

Show more

boolean

true

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__LOAD_ONLY_IF_EMPTY

Show more

boolean

true

Environment variables that are passed to the container.

Environment variable: QUARKUS_REDIS_DEVSERVICES_CONTAINER_ENV

Show more

Map<String,String>

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__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_ENABLED

Show more

boolean

true

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__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_IMAGE_NAME

Show more

string

Optional fixed port the dev service will listen to.

If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_REDIS__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_PORT

Show more

int

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__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_SHARED

Show more

boolean

true

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__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_SERVICE_NAME

Show more

string

redis

Environment variables that are passed to the container.

Environment variable: QUARKUS_REDIS__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_CONTAINER_ENV

Show more

Map<String,String>

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__REDIS_CLIENT_NAME__HOSTS

Show more

list of URI

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__REDIS_CLIENT_NAME__HOSTS_PROVIDER_NAME

Show more

string

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TIMEOUT

Show more

Duration

10S

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__CLIENT_TYPE

Show more

standalone, sentinel, cluster, replication

standalone

The master name (only considered in HA mode).

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__MASTER_NAME

Show more

string

mymaster

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__ROLE

Show more

master, replica, sentinel

master

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__REPLICAS

Show more

never, share, always

never

The default password for cluster/sentinel connections.

If not set it will try to extract the value from the current default #hosts.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__PASSWORD

Show more

string

The maximum size of the connection pool. When working with cluster or sentinel.

This value should be at least the total number of cluster member (or number of sentinels + 1)

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__MAX_POOL_SIZE

Show more

int

6

The maximum waiting requests for a connection from the pool.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__MAX_POOL_WAITING

Show more

int

24

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__POOL_CLEANER_INTERVAL

Show more

Duration

The timeout for a connection recycling.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__POOL_RECYCLE_TIMEOUT

Show more

Duration

15S

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__REDIS_CLIENT_NAME__MAX_WAITING_HANDLERS

Show more

int

2048

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__MAX_NESTED_ARRAYS

Show more

int

32

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__RECONNECT_ATTEMPTS

Show more

int

0

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__RECONNECT_INTERVAL

Show more

Duration

1S

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__PROTOCOL_NEGOTIATION

Show more

boolean

true

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__REDIS_CLIENT_NAME__PREFERRED_PROTOCOL_VERSION

Show more

resp2, resp3

resp3

The TTL of the hash slot cache. A hash slot cache is used by the clustered Redis client to prevent constantly sending CLUSTER SLOTS commands to the first statically configured cluster node.

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__HASH_SLOT_CACHE_TTL

Show more

Duration

1S

TCP config

デフォルト

Set the ALPN usage.

Environment variable: QUARKUS_REDIS_TCP_ALPN

Show more

boolean

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

Sets the list of enabled SSL/TLS protocols.

Environment variable: QUARKUS_REDIS_TCP_SECURE_TRANSPORT_PROTOCOLS

Show more

list of string

Set the idle timeout.

Environment variable: QUARKUS_REDIS_TCP_IDLE_TIMEOUT

Show more

Duration

Set the connect timeout.

Environment variable: QUARKUS_REDIS_TCP_CONNECTION_TIMEOUT

Show more

Duration

Set a list of remote hosts that are not proxied when the client is configured to use a proxy.

Environment variable: QUARKUS_REDIS_TCP_NON_PROXY_HOSTS

Show more

list of string

Set proxy username.

Environment variable: QUARKUS_REDIS_TCP_PROXY_OPTIONS_USERNAME

Show more

string

Set proxy password.

Environment variable: QUARKUS_REDIS_TCP_PROXY_OPTIONS_PASSWORD

Show more

string

Set proxy port. Defaults to 3128.

Environment variable: QUARKUS_REDIS_TCP_PROXY_OPTIONS_PORT

Show more

int

3128

Set proxy host.

Environment variable: QUARKUS_REDIS_TCP_PROXY_OPTIONS_HOST

Show more

string

Set proxy type. Accepted values are: HTTP (default), SOCKS4 and SOCKS5.

Environment variable: QUARKUS_REDIS_TCP_PROXY_OPTIONS_TYPE

Show more

http, socks4, socks5

http

Set the read idle timeout.

Environment variable: QUARKUS_REDIS_TCP_READ_IDLE_TIMEOUT

Show more

Duration

Set the TCP receive buffer size.

Environment variable: QUARKUS_REDIS_TCP_RECEIVE_BUFFER_SIZE

Show more

int

Set the value of reconnect attempts.

Environment variable: QUARKUS_REDIS_TCP_RECONNECT_ATTEMPTS

Show more

int

Set the reconnect interval.

Environment variable: QUARKUS_REDIS_TCP_RECONNECT_INTERVAL

Show more

Duration

Whether to reuse the address.

Environment variable: QUARKUS_REDIS_TCP_REUSE_ADDRESS

Show more

boolean

Whether to reuse the port.

Environment variable: QUARKUS_REDIS_TCP_REUSE_PORT

Show more

boolean

Set the TCP send buffer size.

Environment variable: QUARKUS_REDIS_TCP_SEND_BUFFER_SIZE

Show more

int

Set the SO_linger keep alive duration.

Environment variable: QUARKUS_REDIS_TCP_SO_LINGER

Show more

Duration

Enable the TCP_CORK option - only with linux native transport.

Environment variable: QUARKUS_REDIS_TCP_CORK

Show more

boolean

Enable the TCP_FASTOPEN option - only with linux native transport.

Environment variable: QUARKUS_REDIS_TCP_FAST_OPEN

Show more

boolean

Set whether keep alive is enabled

Environment variable: QUARKUS_REDIS_TCP_KEEP_ALIVE

Show more

boolean

Set whether no delay is enabled

Environment variable: QUARKUS_REDIS_TCP_NO_DELAY

Show more

boolean

Enable the TCP_QUICKACK option - only with linux native transport.

Environment variable: QUARKUS_REDIS_TCP_QUICK_ACK

Show more

boolean

Set the value of traffic class.

Environment variable: QUARKUS_REDIS_TCP_TRAFFIC_CLASS

Show more

int

Set the write idle timeout.

Environment variable: QUARKUS_REDIS_TCP_WRITE_IDLE_TIMEOUT

Show more

Duration

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

Set the ALPN usage.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_ALPN

Show more

boolean

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_APPLICATION_LAYER_PROTOCOLS

Show more

list of string

Sets the list of enabled SSL/TLS protocols.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_SECURE_TRANSPORT_PROTOCOLS

Show more

list of string

Set the idle timeout.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_IDLE_TIMEOUT

Show more

Duration

Set the connect timeout.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_CONNECTION_TIMEOUT

Show more

Duration

Set a list of remote hosts that are not proxied when the client is configured to use a proxy.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_NON_PROXY_HOSTS

Show more

list of string

Set proxy username.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_PROXY_OPTIONS_USERNAME

Show more

string

Set proxy password.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_PROXY_OPTIONS_PASSWORD

Show more

string

Set proxy port. Defaults to 3128.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_PROXY_OPTIONS_PORT

Show more

int

3128

Set proxy host.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_PROXY_OPTIONS_HOST

Show more

string

Set proxy type. Accepted values are: HTTP (default), SOCKS4 and SOCKS5.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_PROXY_OPTIONS_TYPE

Show more

http, socks4, socks5

http

Set the read idle timeout.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_READ_IDLE_TIMEOUT

Show more

Duration

Set the TCP receive buffer size.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_RECEIVE_BUFFER_SIZE

Show more

int

Set the value of reconnect attempts.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_RECONNECT_ATTEMPTS

Show more

int

Set the reconnect interval.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_RECONNECT_INTERVAL

Show more

Duration

Whether to reuse the address.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_REUSE_ADDRESS

Show more

boolean

Whether to reuse the port.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_REUSE_PORT

Show more

boolean

Set the TCP send buffer size.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_SEND_BUFFER_SIZE

Show more

int

Set the SO_linger keep alive duration.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_SO_LINGER

Show more

Duration

Enable the TCP_CORK option - only with linux native transport.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_CORK

Show more

boolean

Enable the TCP_FASTOPEN option - only with linux native transport.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_FAST_OPEN

Show more

boolean

Set whether keep alive is enabled

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_KEEP_ALIVE

Show more

boolean

Set whether no delay is enabled

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_NO_DELAY

Show more

boolean

Enable the TCP_QUICKACK option - only with linux native transport.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_QUICK_ACK

Show more

boolean

Set the value of traffic class.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_TRAFFIC_CLASS

Show more

int

Set the write idle timeout.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TCP_WRITE_IDLE_TIMEOUT

Show more

Duration

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__REDIS_CLIENT_NAME__TCP_LOCAL_ADDRESS

Show more

string

SSL/TLS config

デフォルト

Whether SSL/TLS is enabled.

Environment variable: QUARKUS_REDIS_TLS_ENABLED

Show more

boolean

false

Enable trusting all certificates. Disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_ALL

Show more

boolean

false

PEM Trust config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PEM

Show more

boolean

false

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

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PEM_CERTS

Show more

list of string

JKS config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_JKS

Show more

boolean

false

Path of the key file (JKS format).

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_JKS_PATH

Show more

string

Password of the key file.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_JKS_PASSWORD

Show more

string

PFX config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PFX

Show more

boolean

false

Path to the key file (PFX format).

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PFX_PATH

Show more

string

Password of the key.

Environment variable: QUARKUS_REDIS_TLS_TRUST_CERTIFICATE_PFX_PASSWORD

Show more

string

PEM Key/cert config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PEM

Show more

boolean

false

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

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

JKS config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_JKS

Show more

boolean

false

Path of the key file (JKS format).

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_JKS_PATH

Show more

string

Password of the key file.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_JKS_PASSWORD

Show more

string

PFX config is disabled by default.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PFX

Show more

boolean

false

Path to the key file (PFX format).

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PFX_PATH

Show more

string

Password of the key.

Environment variable: QUARKUS_REDIS_TLS_KEY_CERTIFICATE_PFX_PASSWORD

Show more

string

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

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

Environment variable: QUARKUS_REDIS_TLS_HOSTNAME_VERIFICATION_ALGORITHM

Show more

string

NONE

Whether SSL/TLS is enabled.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_ENABLED

Show more

boolean

false

Enable trusting all certificates. Disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_ALL

Show more

boolean

false

PEM Trust config is disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_PEM

Show more

boolean

false

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_PEM_CERTS

Show more

list of string

JKS config is disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_JKS

Show more

boolean

false

Path of the key file (JKS format).

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_JKS_PATH

Show more

string

Password of the key file.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_JKS_PASSWORD

Show more

string

PFX config is disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_PFX

Show more

boolean

false

Path to the key file (PFX format).

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_PFX_PATH

Show more

string

Password of the key.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_TRUST_CERTIFICATE_PFX_PASSWORD

Show more

string

PEM Key/cert config is disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_PEM

Show more

boolean

false

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_PEM_KEYS

Show more

list of string

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_PEM_CERTS

Show more

list of string

JKS config is disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_JKS

Show more

boolean

false

Path of the key file (JKS format).

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_JKS_PATH

Show more

string

Password of the key file.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_JKS_PASSWORD

Show more

string

PFX config is disabled by default.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_PFX

Show more

boolean

false

Path to the key file (PFX format).

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_PFX_PATH

Show more

string

Password of the key.

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_KEY_CERTIFICATE_PFX_PASSWORD

Show more

string

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

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

Environment variable: QUARKUS_REDIS__REDIS_CLIENT_NAME__TLS_HOSTNAME_VERIFICATION_ALGORITHM

Show more

string

NONE

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

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

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

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

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

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

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

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

関連コンテンツ