Redis Extension Reference Guide
Redis is an in-memory data store used as a database, cache, streaming engine, and message broker. The Quarkus Redis extension allows integrating Quarkus applications with Redis.
To use this extension, the user must be familiar with Redis, especially understanding the mechanism of commands and how they are organized. Typically, we recommend:
-
The interactive tutorial introducing Redis.
-
The command references explains Redis commands and contains links to reference documentation.
This extension provides imperative and reactive APIs and low-level and high-level (type-safe) clients.
1. Use the Redis Client
If you want to use this extension, you need to add the io.quarkus:quarkus-redis
extension first.
In your pom.xml
file, add:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-redis-client</artifactId>
</dependency>
implementation("io.quarkus:quarkus-redis-client")
With this dependency, you can then inject Redis clients or datasource (high-level, type-safe API), such as:
import io.quarkus.redis.datasource.RedisDataSource;
// ...
@Inject RedisAPI lowLevelClient;
@Inject RedisDataSource highLevelApi;
More details about the various APIs offered by the quarkus-redis extension are available in the One extension, multiple APIs section.
To use Redis as a cache backend, refer to the Redis Cache Backend reference. |
2. One extension, multiple APIs
This extension provides multiple ways to interact with Redis:
-
the low-level Vert.x client: it’s a fully reactive, non-blocking, and asynchronous client. More details on the Vert.x Redis Client documentation. Two APIs are exposed:
io.vertx.redis.client.Redis
, andio.vertx.redis.client.RedisAPI
. You will generally use the latter, except if you need to manage connections yourself. -
the low-level Mutiny variant of the Vert.x API: Unlike the previous one, it exposes a Mutiny API and provides both reactive and imperative methods (suffixed with
andAwait()
). Two APIs are exposed:io.vertx.mutiny.redis.client.Redis
andio.vertx.mutiny.redis.client.RedisAPI
. You will generally use the latter, except if you need to manage connections yourself. -
a high-level reactive data source: A type-safe, high-level API to interact with Redis. This API is fully reactive and asynchronous. It exposes a Mutiny API. It exposes the
io.quarkus.redis.datasource.ReactiveRedisDataSource
interface. -
a high-level imperative data source: A type-safe, high-level API to interact with Redis. It is the imperative variant of the reactive data source. It exposes the
io.quarkus.redis.datasource.RedisDataSource
interface.
To help you select the suitable API for you, here are some recommendations:
-
If you are building an imperative (classic) Quarkus application integrating with Redis: use
io.quarkus.redis.datasource.RedisDataSource
. -
If you are building a reactive Quarkus application integrating with Redis: use
io.quarkus.redis.datasource.ReactiveRedisDataSource
. -
If you need fine-grain control, or execute commands in a generic way: use
io.vertx.mutiny.redis.client.RedisAPI
-
If you have existing Vert.x code, use
io.vertx.redis.client.RedisAPI
-
If you need to emit custom commands, you can either use the data sources (reactive or imperative) or the
io.vertx.mutiny.redis.client.Redis
.
3. Inject the default and named clients
This extension lets you configure a default Redis client/data sources or named ones. The latter is essential when you need to connect to multiple Redis instances.
The default connection is configured using the quarkus.redis.*
properties.
For example, to configure the default Redis client, use:
quarkus.redis.hosts=redis://localhost/
When using the default connection, you can inject the various APIS using a plain @Inject
:
@ApplicationScoped
public class RedisExample {
@Inject ReactiveRedisDataSource reactiveDataSource;
@Inject RedisDataSource redisDataSource;
@Inject RedisAPI redisAPI;
// ...
}
In general, you inject a single one; the previous snippet is just an example. |
Named clients are configured using the quarkus.redis.<name>.*
properties:
quarkus.redis.my-redis-1.hosts=redis://localhost/
quarkus.redis.my-redis-2.hosts=redis://my-other-redis:6379
To access the APIs, you need to use the @RedisClientName
qualifier:
@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. Connect to the Redis server
The Redis extension can operate in 4 distinct modes:
-
Simple client (probably what most users need).
-
Sentinel (when working with Redis in High Availability mode).
-
Cluster (when working with Redis in Clustered mode).
-
Replication (single shard, one node writes, multiple read).
The connection url is configured with the quarkus.redis.hosts
(or quarkus.redis.<name>.hosts
) as follows:
quarkus.redis.hosts=redis://[:password@]host[:port][/db-number]
4.1. Use Unix Socket
When using unix-socket, you need:
quarkus.redis.hosts=unix://[:password@]/domain/docker.sock[?select=db-number]
4.2. Use the Sentinel Mode
When using Sentinel, you need to pass multiple host urls and configure the client type to 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.2.1. Automatic Failover
In the sentinel mode, it is possible to configure automatic failover of master connections:
quarkus.redis.auto-failover=true
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.
4.3. Use the Cluster Mode
When using Redis in cluster mode, you need to pass multiple host urls, configure the client type to cluster
and configure the replicas
mode:
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
When using the replication mode, you need to pass a single host url and configure the type to be 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.4.1. Static Topology
In the replication mode, it is possible to reconfigure the Redis client to skip automatic discovery of the topology:
quarkus.redis.topology=static
With static topology, the first node in the configuration is assumed to be a master node, while the remaining nodes are assumed to be replicas. The nodes are not verified; it is a responsibility of the application developer to ensure that the static configuration is correct.
Note that automatic discovery of the topology is usually the preferred choice. Static configuration should only be used when necessary. One such case is Amazon Elasticache for Redis (Cluster Mode Disabled), where:
-
master node should be set to the primary endpoint, and
-
one replica node should be set to the reader endpoint.
Note that the reader endpoint of Elasticache for Redis (Cluster Mode Disabled) is a domain name which resolves to a CNAME record that points to one of the replicas. The CNAME record to which the reader endpoint resolves changes over time. This form of DNS-based load balancing does not work well with DNS resolution caching and connection pooling. As a result, some replicas are likely to be underutilized. |
4.5. Connect to Redis Cloud
To connect to redis cloud, you need the following properties:
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. Use TLS
To use TLS, you need to:
-
Set the
quarkus.redis.tls.enabled=true
property or use the TLS registry (recommended) -
Make sure that your URL starts with
rediss://
(with twos
)
When using the TLS registry, you need to use a named configuration to avoid conflicts with other TLS configurations:
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
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. Configure the authentication
The Redis password can be set in the redis://
URL or with the quarkus.redis.password
property.
We recommend the latter, and if possible, using secrets or an environment variable to configure the password.
The associated environment variable is QUARKUS_REDIS_PASSWORD
, or QUARKUS_REDIS_<NAME>_PASSWORD
for named clients.
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. Use Redis data sources
Quarkus exposes a high-level API on top of Redis. This API is type-safe and structured around the notion of group, inherited from the Redis command organization. This API lets you execute Redis commands more conveniently and safely.
5.1. Inject data sources
For each configured Redis client, two Redis data sources are exposed:
-
io.quarkus.redis.datasource.RedisDataSource
- an imperative (blocking) Redis data source. Each operation blocks until a response is received or a timeout is reached -
io.quarkus.redis.datasource.ReactiveRedisDataSource
- a reactive Redis data source returningUni<X>
orMulti<X>
.
If you configured the default Redis client, you could inject the data sources using:
@Inject RedisDataSource defaultRedisDataSource;
@Inject ReactiveRedisDataSource defaultReactiveRedisDataSource;
If you configured a named Redis client, you need to use the io.quarkus.redis.RedisClientName
qualifier to select the right client:
@RedisClientName("my-redis") RedisDataSource myRedisDataSource;
@RedisClientName("my-redis") ReactiveRedisDataSource myReactiveRedisDataSource;
When using the blocking variant, you can configure the default timeout with:
quarkus.redis.timeout=5s
quarkus.redis.my-redis.timeout=5s
The default timeout is configured to 10s.
All about delegation
The blocking data source ( |
5.1.1. Data Source groups
As mentioned above, the API is divided into groups:
-
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()
(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. Also the module has been declared end of life by Redis. -
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.
Each of these methods returns an object that lets you execute the commands related to the group. The following snippet demonstrates how to use the hash group:
@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 | Inject the RedisDataSource in the constructor |
2 | Creates the HashCommands object.
This object has three type parameters: the type of the key, the type of the field, and the type of the member |
3 | Use the created commands to associate the field field with the value value |
4 | Use the created commands to retrieve the field field value. |
5.2. Serializing and Deserializing data
The data source APIs handle the serialization and deserialization automatically.
By default, non-standard types are serialized into JSON and deserialized from JSON.
In this case, quarkus-jackson
is used.
5.4. Custom codec
You can register custom codec by providing a CDI bean implementing the io.quarkus.redis.datasource.codecs.Codec
interface:
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]);
}
}
The canHandle
method is called to check if the codec can handle a specific type.
The parameter received in the encode
method matches that type.
The object returned by the decode
method must also match that type.
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
The value
group is used to manipulate Redis Strings.
Thus, this group is not limited to Java Strings but can be used for integers (like a counter) or binary content (like images).
5.6.1. Work with cached values
You can use Redis as a cache using the setex
command, which stores a given value to a given key for a given duration.
The following snippet shows how such a command can be used to store BusinessObject
for 1 second.
@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
}
}
You can use the setnx
method only to set the value if no value has been stored for the given key.
The key group provides more fine-grain control on expiration and ttl of each key.
|
The
|
5.6.2. Store binary data
Redis strings can be used to store binary data, such as images.
In this case, we will use byte[]
as value type:
@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. Store a counter
You can store counters in Redis as demonstrated below:
@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 | Retrieve the commands.
This time we will manipulate Long values |
2 | Retrieve the counter associated with the given key .
Return 0L when no counter is stored. |
3 | Increment the value.
If there are no counter stored for the key, the incr command considers 0 as value (so incr sets the value to 1). |
There are other methods that can be useful to manipulate counters, such as:
-
incrby
- allows setting the increment value (positive or negative) -
incrbyfloat
- allows setting the increment value as a float/ double (the stored value will be a double) -
set
- to set an initial value if needed -
decr
anddecrby
- allows decrementing the stored value
5.6.4. Communicate with pub/sub
Redis allows sending messages to channels and listening for these messages.
These features are available from the pubsub
group.
The following snippets shows how a cache can emit a Notification
after every set
, and how a subscriber can receive the 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. Use Redis transactions
Redis transactions are slightly different from relational database transactions. Redis transactions are a batch of commands executed altogether.
A Redis transaction can watch a set of keys, which would discard the transaction is one of these keys are updated during the transaction execution.
Commands enqueued in a transaction are not executed before the whole transaction is executed.
It means that you cannot retrieve a result during the transaction.
Results are accumulated in a TransactionResult
object you will access after the completion of the transaction.
This object contains whether the transaction succeeded or was discarded, and in the former case the result of each command (indexed by the command order).
To start a transaction, you use the withTransaction
method.
This method receives a Consumer<TransactionalRedisDataSource>
, which follows the same API as the regular RedisDataSource
except that the commands return void
(Uni<Void>
for the reactive variant).
When that consumer returns, the transaction is executed.
The following snippet shows how to create a transaction executing two related writes:
@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");
});
The received tx
object can also be used to discard the transaction, using: tx.discard();
.
The returned TransactionResult
lets you retrieve the result of each command.
When using the reactive variant of the data source, the passed callback is a 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"));
});
Transaction execution can be conditioned by keys.
When a passed key gets modified during the execution of a transaction, the transaction is discarded.
The keys are passed as String
as a second parameter to the withTransaction
method:
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);
You cannot use the pub/sub feature from within a transaction. |
5.6.6. Implement the optimistic locking pattern
To use optimistic locking, you need to use a variant of the withTransaction
method, allowing the execution of code before the transaction starts.
In other words, it will be executed as follows:
WATCH key
// Pre-transaction block
// ....
// Produce a result
MULTI
// In transaction code, receive the result produced by the pre-transaction block.
EXEC
For example, if you need to update a value in a hash only if the field exists, you will use the following 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
If one of the watched keys is touched before or during the execution of the pre-transaction or transactional blocks, the transaction is aborted. The pre-transactional block produces a result that the transactional block can use. This construct is necessary because, within a transaction, the commands do not produce a result. Results can only be retrieved after the execution of the transaction.
The pre-transaction and transactional blocks are invoked on the same Redis connection. Consequently, the pre-transaction block must use the passed data source to execute commands. Thus, the commands are emitted from that connection. These commands must not modify the watched keys.
The transaction is aborted if the pre-transaction block throws an exception (or produces a failure when using the reactive API).
5.6.7. Execute custom commands
To execute a custom command, or a command not supported by the API, use the following approach:
@Inject ReactiveRedisDataSource ds;
// ...
Response response = ds.execute("my-command", param1, param2, param3);
The execute
method sends the command to Redis and retrieves the Response
.
The command name is passed as first parameters.
You can add an arbitrary number of String parameters to your command.
The result is wrapped into a Response
object.
The reactive variant returns a Uni<Response>
.
You can also execute custom command in a transaction. |
6. Preload data into Redis
On startup, you can configure the Redis client to preload data into the Redis database.
6.1. Configure the 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. Write load scripts
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. Configure the pre-loading
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. Distinguish dev/test vs. prod when pre-loading
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, make 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. Use the Vert.x redis client
In addition to the high-level API, you can use the Vertx Redis clients directly in your code. The documentation of the Vert.x Redis Client is available on the Vert.x Web Site.
8. Configure Redis hosts programmatically
The RedisHostsProvider
programmatically provides redis hosts.
This allows for configuration of properties like redis connection password coming from other sources.
This is useful as it removes the need to store sensitive data in 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));
}
}
The host provider can be used to configure the redis client like shown below
quarkus.redis.hosts-provider-name=hosts-provider
9. Customize the Redis options programmatically
You can expose a bean implementing the io.quarkus.redis.client.RedisOptionsCustomizer
interface to customize the Redis client options.
The bean is called for each configured Redis client:
@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. Use the Redis Dev Services
See Redis Dev Service.
10. Configure Redis observability
10.1. Enable the health checks
If you are using the quarkus-smallrye-health
extension, quarkus-redis
will automatically add a readiness health check to validate the connection to the Redis server.
So when you access the /q/health/ready
endpoint of your application you will have information about the connection validation status.
This behavior can be disabled by setting the quarkus.redis.health.enabled
property to false
in your application.properties
.
10.2. Enable metrics
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.
Como exemplo, se você exportar as métricas para o Prometheus, obterá:
# 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. Configuration reference
Propriedade de Configuração Fixa no Momento da Compilação - Todas as outras propriedades de configuração podem ser sobrepostas em tempo de execução.
Configuration property |
Tipo |
Padrão |
---|---|---|
A list of files allowing to pre-load data into the Redis server. The file is formatted as follows:
Environment variable: Show more |
list of string |
|
When using Environment variable: Show more |
boolean |
|
When using Environment variable: Show more |
boolean |
|
Whether a health check is published in case the smallrye-health extension is present. Environment variable: Show more |
boolean |
|
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 Environment variable: Show more |
list of URI |
|
The hosts provider bean name. It is the Used when Environment variable: Show more |
string |
|
The maximum delay to wait before a blocking command to Redis server times out Environment variable: Show more |
|
|
The Redis client type. Accepted values are: Environment variable: Show more |
|
|
The master name (only considered in the Sentinel mode). Environment variable: Show more |
string |
|
The role name (only considered in the Sentinel mode). Accepted values are: Environment variable: Show more |
|
|
Whether to use replicas nodes (only considered in Cluster mode and Replication mode). Accepted values are: Environment variable: Show more |
|
|
The default password for Redis connections. If not set, it will try to extract the value from the Environment variable: Show more |
string |
|
The maximum size of the connection pool. Environment variable: Show more |
int |
|
The maximum waiting requests for a connection from the pool. Environment variable: Show more |
int |
|
The duration indicating how often should the connection pool cleaner execute. Environment variable: Show more |
|
|
The timeout for unused connection recycling. Environment variable: Show more |
|
|
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: Show more |
int |
|
Tune how much nested arrays are allowed on a Redis response. This affects the parser performance. Environment variable: Show more |
int |
|
The number of reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
int |
|
The interval between reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
|
|
Should the client perform Environment variable: Show more |
boolean |
|
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: Show more |
|
|
The TTL of the hash slot cache. A hash slot cache is used by the clustered Redis client to prevent constantly sending This setting is only meaningful in case of a clustered Redis client and has no effect otherwise. Environment variable: Show more |
|
|
Whether automatic failover is enabled. This only makes sense for sentinel clients with role of 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: Show more |
boolean |
|
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: Show more |
|
|
The client name used to identify the connection. If the If the Environment variable: Show more |
string |
|
Whether it should set the client name while connecting with Redis. This is necessary because Redis only accepts This property can be used with Environment variable: Show more |
boolean |
|
The name of the TLS configuration to use. If a name is configured, it uses the configuration from If no TLS configuration name is set then, The default TLS configuration is not used by default. Environment variable: Show more |
string |
|
A list of files allowing to pre-load data into the Redis server. The file is formatted as follows:
Environment variable: Show more |
list of string |
|
When using Environment variable: Show more |
boolean |
|
When using Environment variable: Show more |
boolean |
|
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 Environment variable: Show more |
list of URI |
|
The hosts provider bean name. It is the Used when Environment variable: Show more |
string |
|
The maximum delay to wait before a blocking command to Redis server times out Environment variable: Show more |
|
|
The Redis client type. Accepted values are: Environment variable: Show more |
|
|
The master name (only considered in the Sentinel mode). Environment variable: Show more |
string |
|
The role name (only considered in the Sentinel mode). Accepted values are: Environment variable: Show more |
|
|
Whether to use replicas nodes (only considered in Cluster mode and Replication mode). Accepted values are: Environment variable: Show more |
|
|
The default password for Redis connections. If not set, it will try to extract the value from the Environment variable: Show more |
string |
|
The maximum size of the connection pool. Environment variable: Show more |
int |
|
The maximum waiting requests for a connection from the pool. Environment variable: Show more |
int |
|
The duration indicating how often should the connection pool cleaner execute. Environment variable: Show more |
|
|
The timeout for unused connection recycling. Environment variable: Show more |
|
|
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: Show more |
int |
|
Tune how much nested arrays are allowed on a Redis response. This affects the parser performance. Environment variable: Show more |
int |
|
The number of reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
int |
|
The interval between reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
|
|
Should the client perform Environment variable: Show more |
boolean |
|
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: Show more |
|
|
The TTL of the hash slot cache. A hash slot cache is used by the clustered Redis client to prevent constantly sending This setting is only meaningful in case of a clustered Redis client and has no effect otherwise. Environment variable: Show more |
|
|
Whether automatic failover is enabled. This only makes sense for sentinel clients with role of 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: Show more |
boolean |
|
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: Show more |
|
|
The client name used to identify the connection. If the If the Environment variable: Show more |
string |
|
Whether it should set the client name while connecting with Redis. This is necessary because Redis only accepts This property can be used with Environment variable: Show more |
boolean |
|
The name of the TLS configuration to use. If a name is configured, it uses the configuration from If no TLS configuration name is set then, The default TLS configuration is not used by default. Environment variable: Show more |
string |
|
Tipo |
Padrão |
|
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: Show more |
boolean |
|
The container image name to use, for container based DevServices providers. If you want to use Redis Stack modules (bloom, graph, search…), use: Environment variable: Show more |
string |
|
Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly. Environment variable: 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 Container sharing is only used in dev mode. Environment variable: Show more |
boolean |
|
The value of the This property is used when you need multiple shared Redis servers. Environment variable: Show more |
string |
|
Environment variables that are passed to the container. Environment variable: Show more |
Map<String,String> |
|
Tipo |
Padrão |
|
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: Show more |
boolean |
|
The container image name to use, for container based DevServices providers. If you want to use Redis Stack modules (bloom, graph, search…), use: Environment variable: Show more |
string |
|
Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly. Environment variable: 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 Container sharing is only used in dev mode. Environment variable: Show more |
boolean |
|
The value of the This property is used when you need multiple shared Redis servers. Environment variable: Show more |
string |
|
Environment variables that are passed to the container. Environment variable: Show more |
Map<String,String> |
|
Tipo |
Padrão |
|
boolean |
||
Sets the list of application-layer protocols to provide to the server during the Environment variable: Show more |
list of string |
|
Sets the list of enabled SSL/TLS protocols. Environment variable: Show more |
list of string |
|
Set the idle timeout. Environment variable: Show more |
||
Set the connect timeout. Environment variable: Show more |
||
Set a list of remote hosts that are not proxied when the client is configured to use a proxy. Environment variable: Show more |
list of string |
|
Set proxy username. Environment variable: Show more |
string |
|
Set proxy password. Environment variable: Show more |
string |
|
Set proxy port. Defaults to 3128. Environment variable: Show more |
int |
|
Set proxy host. Environment variable: Show more |
string |
|
Set proxy type. Accepted values are: Environment variable: Show more |
|
|
Set the read idle timeout. Environment variable: Show more |
||
Set the TCP receive buffer size. Environment variable: Show more |
int |
|
Set the value of reconnect attempts. Environment variable: Show more |
int |
|
Set the reconnect interval. Environment variable: Show more |
||
Whether to reuse the address. Environment variable: Show more |
boolean |
|
Whether to reuse the port. Environment variable: Show more |
boolean |
|
Set the TCP send buffer size. Environment variable: Show more |
int |
|
Set the Environment variable: Show more |
||
Enable the Environment variable: Show more |
boolean |
|
Enable the Environment variable: Show more |
boolean |
|
Set whether keep alive is enabled Environment variable: Show more |
boolean |
|
Set whether no delay is enabled Environment variable: Show more |
boolean |
|
Enable the Environment variable: Show more |
boolean |
|
Set the value of traffic class. Environment variable: Show more |
int |
|
Set the write idle timeout. Environment variable: Show more |
||
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: Show more |
string |
|
Tipo |
Padrão |
|
Whether SSL/TLS is enabled. Environment variable: Show more |
boolean |
|
Enable trusting all certificates. Disabled by default. Environment variable: Show more |
boolean |
|
PEM Trust config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the trust certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
PEM Key/cert config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the path to the key files (Pem format). Environment variable: Show more |
list of string |
|
Comma-separated list of the path to the certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
The hostname verification algorithm to use in case the server’s identity should be checked. Should be If set to Environment variable: Show more |
string |
|
Tipo |
Padrão |
|
Set the ALPN usage. Environment variable: Show more |
boolean |
|
Sets the list of application-layer protocols to provide to the server during the Environment variable: Show more |
list of string |
|
Sets the list of enabled SSL/TLS protocols. Environment variable: Show more |
list of string |
|
Set the idle timeout. Environment variable: Show more |
||
Set the connect timeout. Environment variable: Show more |
||
Set a list of remote hosts that are not proxied when the client is configured to use a proxy. Environment variable: Show more |
list of string |
|
Set proxy username. Environment variable: Show more |
string |
|
Set proxy password. Environment variable: Show more |
string |
|
Set proxy port. Defaults to 3128. Environment variable: Show more |
int |
|
Set proxy host. Environment variable: Show more |
string |
|
Set proxy type. Accepted values are: Environment variable: Show more |
|
|
Set the read idle timeout. Environment variable: Show more |
||
Set the TCP receive buffer size. Environment variable: Show more |
int |
|
Set the value of reconnect attempts. Environment variable: Show more |
int |
|
Set the reconnect interval. Environment variable: Show more |
||
Whether to reuse the address. Environment variable: Show more |
boolean |
|
Whether to reuse the port. Environment variable: Show more |
boolean |
|
Set the TCP send buffer size. Environment variable: Show more |
int |
|
Set the Environment variable: Show more |
||
Enable the Environment variable: Show more |
boolean |
|
Enable the Environment variable: Show more |
boolean |
|
Set whether keep alive is enabled Environment variable: Show more |
boolean |
|
Set whether no delay is enabled Environment variable: Show more |
boolean |
|
Enable the Environment variable: Show more |
boolean |
|
Set the value of traffic class. Environment variable: Show more |
int |
|
Set the write idle timeout. Environment variable: Show more |
||
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: Show more |
string |
|
Tipo |
Padrão |
|
Whether SSL/TLS is enabled. Environment variable: Show more |
boolean |
|
Enable trusting all certificates. Disabled by default. Environment variable: Show more |
boolean |
|
PEM Trust config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the trust certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
PEM Key/cert config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the path to the key files (Pem format). Environment variable: Show more |
list of string |
|
Comma-separated list of the path to the certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
The hostname verification algorithm to use in case the server’s identity should be checked. Should be If set to Environment variable: Show more |
string |
|
About the Duration format
To write duration values, use the standard Você também pode usar um formato simplificado, começando com um número:
Em outros casos, o formato simplificado é traduzido para o formato 'java.time.Duration' para análise:
|