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

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

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

このエクステンションを使うには、ユーザーが Redis に精通していること、特にコマンドの仕組みとその設定について理解していることが必要です。一般的には、以下を推奨します。

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

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

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

1. インストール

このエクステンションを使用する場合は、最初に 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")

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

import io.quarkus.redis.datasource.RedisDataSource;

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

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

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 を使用してさまざまな 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;
    // ...
}
You can omit the @Inject annotation when using @RedisClientName.

4. Connection to 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 Socket

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

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

4.2. Sentinel モード

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 my-master
quarkus.redis.role=master # master is the default

4.3. クラスターモード

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

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

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

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

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

4.5. Redis Cloud

redis クラウドに接続するためには、以下のプロパティーが必要です。

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. 認証

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

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

5. Quarkus client API for data sources

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

5.1. Inject data sources

設定された各 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()

  • 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)

  • transactions - withTransaction

  • json - .json() (requires the RedisJSON module on the server side)

  • bloom - .bloom() (requires the RedisBloom module on the server side)

  • cuckoo - .cuckoo() (requires the rRedisBloom module on the server side, which also provides the cuckoo filter commands)

  • count-min - .countmin() (requires the RedisBloom module on the server side, which also provides the count-min filter commands)

  • top-k - .topk() (requires the RedisBloom module on the server side, which also provides the top-k filter commands)

  • graph - .graph() (requires the RedisGraph module on the server side). These commands are marked as experimental, as we would need feedback before making them stable.

  • search - .search() (requires the RedisSearch module on the server side).

  • auto-suggest - .autosuggest() (requires the RedisSearch module on the server side).

  • time-series - .timeseries() (requires the Redis Time Series module on the server side).

These commands are marked as experimental, as we would need feedback before making them stable.

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

@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 が使用されます。

バイナリーデータを格納するには、byte[] を使用します。

5.3. value グループ

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

5.3.1. Work with cached values

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.3.2. Store binary data

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.3.3. Store a counter

以下に示すように、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.3.4. Communicate with pub/sub

Redis allows sending messages to channels and listening for these messages. These features are available from the pubsub group.

以下のスニペットは、キャッシュ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.3.5. Redis transactions

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.3.6. Optimistic locking

楽観ロックを使用するには、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.3.7. Execute custom commands

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

@Inject ReactiveRedisDataSource ds;

// ...

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

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

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

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

6. Preload data into Redis

On startup, you can configure the Redis client to preload data into the Redis database.

6.1. Load scripts

Specify the load script you want to load using:

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 is a build time property than cannot be overridden at runtime.

Note that each client can have a different script, even a list of scripts. In the case of a list, the data is imported in the list order (for example, first actors.redis, then movies.redis for the my-redis client).

6.2. Load Script format

The .redis file follows a one command per line format:

# 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 batches all the commands from a single file and sends all the commands. The loading process fails if there is any error, but the previous instructions may have been executed. To avoid that, you can wrap your command into a Redis transaction:

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

6.3. Configuration

The data is loaded when the application starts. By default, it drops the whole database before importing. You can prevent this using quarkus.redis.flush-before-load=false.

Also, the import process only runs if the database is empty (no key). You can force to import even if there is data using the quarkus.redis.load-only-if-empty=false

6.4. Dev/Test vs. Prod

As mentioned above, in dev and test modes, Quarkus tries to import data by looking for the src/main/resources/import.redis. This behavior is disabled in prod mode, and if you want to import even in production, add:

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

Before importing in prod mode, mae sure you configured quarkus.redis.flush-before-load accordingly.

In dev mode, to reload the content of the .redis load scripts, you need to add: %dev.quarkus.vertx.caching=false

7. Vert.x Redis クライアント

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

8. Redis ヘルスチェック

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

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

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

9. Programmatic Redis Hosts

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

10. Customize the Redis options programmatically

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);
        }
    }
}

10.1. Dev Services

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

11. Redis client metrics

11.1. Enable metrics collection

Redis client metrics are automatically enabled when the application also uses the quarkus-micrometer extension. Micrometer collects the metrics of all the Redis clients implemented by the application.

例えば、メトリクスを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

The Redis client name can be found in the tags.

The metrics contain both the Redis connection pool metrics (redis_pool_*) and the metrics about the command execution (redis_commands_*) such as the number of command, successes, failures, and durations.

11.2. Disable metrics collection

To disable the Redis client metrics when quarkus-micrometer is used, add the following property to the application configuration:

quarkus.micrometer.binder.redis.enabled=false

12. Configuration reference

ビルド時に固定される設定プロパティ - その他の設定プロパティはランタイムでオーバーライド可能です。

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

list of 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

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

boolean

true

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

Environment variable: QUARKUS_REDIS_HEALTH_ENABLED

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

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-server:latest.

Environment variable: QUARKUS_REDIS_DEVSERVICES_IMAGE_NAME

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

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

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

string

redis

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

list of 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

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

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__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_ENABLED

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-server:latest.

Environment variable: QUARKUS_REDIS__ADDITIONAL_REDIS_CLIENTS__DEVSERVICES_IMAGE_NAME

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

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

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

string

redis