Connecting Redis¶
Connections to a Redis Standalone, Sentinel, or Cluster require a
specification of the connection details. The unified form is RedisURI.
You can provide the database, password and timeouts within the
RedisURI. You have following possibilities to create a RedisURI:
-
Use an URI:
-
Use the Builder
-
Set directly the values in
RedisURI
URI syntax¶
Redis Standalone
redis :// [[username :] password@] host [:port][/database]
[?[timeout=timeout[d|h|m|s|ms|us|ns]] [&clientName=clientName]
[&libraryName=libraryName] [&libraryVersion=libraryVersion] ]
Redis Standalone (SSL)
rediss :// [[username :] password@] host [: port][/database]
[?[timeout=timeout[d|h|m|s|ms|us|ns]] [&clientName=clientName]
[&libraryName=libraryName] [&libraryVersion=libraryVersion] ]
Redis Standalone (Unix Domain Sockets)
redis-socket :// [[username :] password@]path
[?[timeout=timeout[d|h|m|s|ms|us|ns]] [&database=database]
[&clientName=clientName] [&libraryName=libraryName]
[&libraryVersion=libraryVersion] ]
Redis Sentinel
redis-sentinel :// [[username :] password@] host1[:port1] [, host2[:port2]] [, hostN[:portN]] [/database]
[?[timeout=timeout[d|h|m|s|ms|us|ns]] [&sentinelMasterId=sentinelMasterId]
[&clientName=clientName] [&libraryName=libraryName]
[&libraryVersion=libraryVersion] ]
Schemes
-
redisRedis Standalone -
redissRedis Standalone SSL -
redis-socketRedis Standalone Unix Domain Socket -
redis-sentinelRedis Sentinel
Timeout units
-
dDays -
hHours -
mMinutes -
sSeconds -
msMilliseconds -
usMicroseconds -
nsNanoseconds
Hint: The database parameter within the query part has higher precedence than the database in the path.
RedisURI supports Redis Standalone, Redis Sentinel and Redis Cluster with plain, SSL, TLS and unix domain socket connections.
Hint: The database parameter within the query part has higher precedence than the database in the path. RedisURI supports Redis Standalone, Redis Sentinel and Redis Cluster with plain, SSL, TLS and unix domain socket connections.
Authentication¶
Redis URIs may contain authentication details that effectively lead to
usernames with passwords, password-only, or no authentication.
Connections are authenticated by using the information provided through
RedisCredentials. Credentials are obtained at connection time from a
CredentialsProvider, which resolves credentials asynchronously as a
CompletionStage and does not require Project Reactor. When configuring
username/password on the URI statically, a StaticCredentialsProvider
holds the configured information.
The reactive RedisCredentialsProvider, which resolves credentials as a
Mono, is deprecated since 7.9 in favor of CredentialsProvider. Your
own RedisCredentialsProvider implementations still work — a
RedisCredentialsProvider is a CredentialsProvider, and providers
configured through the deprecated API are adapted automatically.
As of Lettuce 8.0, the built-in providers — StaticCredentialsProvider
and TokenBasedRedisCredentialsProvider — implement only
CredentialsProvider and no longer implement RedisCredentialsProvider.
Code that assigns them to a RedisCredentialsProvider, calls
resolveCredentials() or credentials() on them, or casts the result
of the deprecated RedisURI.getCredentialsProvider() to one of them must
use CredentialsProvider (resolveCredentialsAsync(),
subscribeToCredentials(...), RedisURI.getCredentialsProviderAsync())
or wrap the provider with RedisCredentialsProvider.adapt(...).
If an API still requires a RedisCredentialsProvider, for example a
Spring Data Redis RedisCredentialsProviderFactory, wrap your
CredentialsProvider with RedisCredentialsProvider.adapt(...). The
adapted provider streams whenever the original one does, so connections
are still re-authenticated when new credentials are emitted:
Notes
-
When using Redis Sentinel, the password from the URI applies to the data nodes only. Sentinel authentication must be configured for each sentinel node.
-
Usernames are supported as of Redis 6.
-
Library name and library version are automatically set on Redis 7.2 or greater.
Basic Usage¶
RedisClient client = RedisClient.create("redis://localhost");
StatefulRedisConnection<String, String> connection = client.connect();
RedisCommands<String, String> commands = connection.sync();
String value = commands.get("foo");
...
connection.close();
client.shutdown();
-
Create the
RedisClientinstance and provide a Redis URI pointing to localhost, Port 6379 (default port). -
Open a Redis Standalone connection. The endpoint is used from the initialized
RedisClient -
Obtain the command API for synchronous execution. Lettuce supports asynchronous and reactive execution models, too.
-
Issue a
GETcommand to get the keyfoo. -
Close the connection when you’re done. This happens usually at the very end of your application. Connections are designed to be long-lived.
-
Shut down the client instance to free threads and resources. This happens usually at the very end of your application.
Each Redis command is implemented by one or more methods with names
identical to the lowercase Redis command name. Complex commands with
multiple modifiers that change the result type include the CamelCased
modifier as part of the command name, e.g. zrangebyscore and
zrangebyscoreWithScores.
Redis connections are designed to be long-lived and thread-safe, and if
the connection is lost will reconnect until close() is called. Pending
commands that have not timed out will be (re)sent after successful
reconnection.
All connections inherit a default timeout from their RedisClient and
and will throw a RedisException when non-blocking commands fail to
return a result before the timeout expires. The timeout defaults to 60
seconds and may be changed in the RedisClient or for each connection.
Synchronous methods will throw a RedisCommandExecutionException in
case Redis responds with an error. Asynchronous connections do not throw
exceptions when Redis responds with an error.
RedisURI¶
The RedisURI contains the host/port and can carry
authentication/database details. On a successful connect you get
authenticated, and the database is selected afterward. This applies
also after re-establishing a connection after a connection loss.
A Redis URI can also be created from an URI string. Supported formats are:
-
redis://[password@]host[:port][/databaseNumber]Plaintext Redis connection -
rediss://[password@]host[:port][/databaseNumber]SSL Connections Redis connection -
redis-sentinel://[password@]host[:port][,host2[:port2]][/databaseNumber]#sentinelMasterIdfor using Redis Sentinel -
redis-socket:///path/to/socketUnix Domain Sockets connection to Redis
Exceptions¶
In the case of an exception/error response from Redis, you’ll receive a
RedisException containing
the error message. RedisException is a RuntimeException.
Examples¶
RedisURI uri = new RedisURI("localhost", 6379, Duration.ofSeconds(20));
RedisClient client = RedisClient.create(uri);
// …
client.shutdown();
RedisURI redisUri = RedisURI.Builder.redis("localhost")
.withPassword("authentication")
.withDatabase(2)
.build();
RedisClient client = RedisClient.create(redisUri);
// …
client.shutdown();
RedisURI redisUri = RedisURI.Builder.redis("localhost")
.withSsl(true)
.withPassword("authentication")
.withDatabase(2)
.build();
RedisClient client = RedisClient.create(redisUri);
// …
client.shutdown();
RedisURI redisUri = RedisURI.create("redis://authentication@localhost/2");
RedisClient client = RedisClient.create(redisUri);
// …
client.shutdown();
Streaming Credentials Provider¶
Lettuce 6.6.0 added support for streaming credentials.
It is useful when you need to refresh credentials periodically. Example use cases include: token expiration, rotating credentials, etc.
A connection configured with a CredentialsProvider that supports streaming is re-authenticated automatically when new credentials are emitted and ReauthenticateBehavior is set to ON_NEW_CREDENTIALS.
A streaming provider returns true from supportsStreaming() and pushes updates through subscribeToCredentials(Consumer<RedisCredentials> onNext, Consumer<Throwable> onError). That method returns a Subscription, which the client closes to stop receiving updates. This is the reactor-free replacement for the deprecated reactive credentials() stream.
Step 1 - Create a Streaming Credentials Provider¶
A simple example of a streaming credentials provider that emits new credentials. Replay semantics on subscription are
implementation-defined (see CredentialsProvider#subscribeToCredentials): this sample replays the most recent
successful credentials to a new subscriber and does not retain prior errors for replay to subscribers added later.
public class MyStreamingCredentialsProvider implements CredentialsProvider, AutoCloseable {
private final List<Listener> listeners = new CopyOnWriteArrayList<>();
private final AtomicReference<CompletableFuture<RedisCredentials>> credentialsFutureRef =
new AtomicReference<>(new CompletableFuture<>());
private volatile boolean closed;
@Override
public boolean supportsStreaming() {
return true;
}
@Override
public CompletionStage<RedisCredentials> resolveCredentialsAsync() {
// Return a fresh wrapper so callers cannot complete the provider's internal future.
CompletableFuture<RedisCredentials> result = new CompletableFuture<>();
credentialsFutureRef.get().whenComplete((creds, t) -> {
if (t != null) {
result.completeExceptionally(t);
} else {
result.complete(creds);
}
});
return result;
}
@Override
public Subscription subscribeToCredentials(Consumer<RedisCredentials> onNext,
Consumer<Throwable> onError) {
if (closed) {
throw new IllegalStateException("Credentials provider closed");
}
Listener listener = new Listener(onNext, onError);
listeners.add(listener);
// Replay the latest known credentials, if any, to synchronize the new subscriber.
CompletableFuture<RedisCredentials> latest = credentialsFutureRef.get();
if (latest.isDone() && !latest.isCompletedExceptionally()) {
onNext.accept(latest.getNow(null));
}
return () -> listeners.remove(listener);
}
@Override
public void close() {
closed = true;
listeners.clear();
CompletableFuture<RedisCredentials> pending = credentialsFutureRef.get();
if (!pending.isDone()) {
pending.completeExceptionally(new IllegalStateException("Credentials provider closed"));
}
}
// Emit new credentials when needed.
public void emitCredentials(String username, char[] password) {
if (closed) {
return;
}
RedisCredentials credentials = RedisCredentials.just(username, password);
CompletableFuture<RedisCredentials> previous = credentialsFutureRef
.getAndSet(CompletableFuture.completedFuture(credentials));
if (!previous.isDone()) {
previous.complete(credentials);
}
for (Listener l : listeners) {
l.onNext.accept(credentials);
}
}
// Emit a transient error. Delivered live to existing subscribers and to any in-flight
// resolveCredentialsAsync() waiter; not retained for replay to subscribers added later.
public void emitError(Throwable error) {
if (closed) {
return;
}
CompletableFuture<RedisCredentials> previous = credentialsFutureRef.get();
if (!previous.isDone() && credentialsFutureRef.compareAndSet(previous, new CompletableFuture<>())) {
previous.completeExceptionally(error);
}
for (Listener l : listeners) {
l.onError.accept(error);
}
}
private static class Listener {
final Consumer<RedisCredentials> onNext;
final Consumer<Throwable> onError;
Listener(Consumer<RedisCredentials> onNext, Consumer<Throwable> onError) {
this.onNext = onNext;
this.onError = onError;
}
}
}
Notes on the sample:
- No explicit locking is used.
CopyOnWriteArrayListmakes subscriber iteration safe against concurrent add/remove, andAtomicReferencemakes the latest-credentials swap atomic. This leaves one race: ifsubscribeToCredentialsreads the latest credentials whileemitCredentialsruns, the new subscriber can receive the new credentials first and the replayed previous ones afterwards, re-authenticating with stale credentials. Providers that emit credentials concurrently with subscriptions should serialize the two, for example by running emission and replay on a single-threadedExecutoror by making both methodssynchronized. subscribeToCredentialsandemitCredentialsdispatch on the caller thread for brevity. Production providers should consider hopping to a dedicatedExecutorso that subscriber callbacks cannot block the thread that drives credential renewal.
Step 2 - Create a RedisURI with streaming credentials provider¶
// Create a streaming credentials provider
MyStreamingCredentialsProvider streamingCredentialsProvider = new MyStreamingCredentialsProvider();
// Emit initial credentials
streamingCredentialsProvider.emitCredentials("testuser", "testpass".toCharArray());
// Enable automatic re-authentication
ClientOptions clientOptions = ClientOptions.builder()
// enable automatic re-authentication
.reauthenticateBehavior(ClientOptions.ReauthenticateBehavior.ON_NEW_CREDENTIALS)
.build();
// Create a RedisURI with streaming credentials provider
RedisURI redisURI = RedisURI.builder().withHost(HOST).withPort(PORT)
.withAuthentication(streamingCredentialsProvider)
.build();
// RedisClient
RedisClient redisClient = RedisClient.create(redisURI);
redisClient.setOptions(clientOptions);
redisClient.connect().sync().ping();
// ...
// Emit new credentials when needed
streamingCredentialsProvider.emitCredentials("testuser", "password-rotated".toCharArray());
Note
The reactive
RedisCredentialsProviderstreaming API —resolveCredentials()returningMono<RedisCredentials>andcredentials()returningFlux<RedisCredentials>— is deprecated since 7.9 in favor ofCredentialsProviderandsubscribeToCredentials(...). Existing reactive providers continue to work.
Microsoft Entra ID Authentication¶
Lettuce 6.6.0 introduces built-in support for authentication with Azure Managed Redis and Azure Cache for Redis using Microsoft Entra ID (formerly Azure Active Directory). It enables seamless integration with Azure's Redis services by fetching authentication tokens and managing the token renewal in the background. Integration is built on top of redis-authx library, and provides support for:
- System-assigned managed identity
- User-assigned managed identity
- Service principal
You can learn more about managed identities in the Microsoft Entra ID documentation.
Basic Usage¶
Pre-requisites¶
- register an application and create a service principal in Azure.
- Create a Redis cache in Azure and grant your service principal access: AMR or ACR documentation.
Step 1 - Add the dependencies¶
Lettuce requires redis-authx-entraid dependency to provide Microsoft Entra ID authentication support. Make sure to include that dependency on your classpath.
If using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>redis.clients.authentication</groupId>
<artifactId>redis-authx-entraid</artifactId>
<version>0.2.0</version>
</dependency>
Step 2 - Create Entra ID enabled credentials provider¶
The lifecycle of the credentials provider is not managed by the Lettuce client. You can create it once and reuse it across multiple clients\connections. When no longer needed, you should close the provider to release resources TokenBasedRedisCredentialsProvider#close.
Create Microsoft Entra ID enabled credentials provider¶
// Entra ID enabled credentials provider for Service Principle Identity with Client Secret
TokenBasedRedisCredentialsProvider credentialsSP;
try ( EntraIDTokenAuthConfigBuilder builder = EntraIDTokenAuthConfigBuilder.builder()) {
builder.clientId(CLIENT_ID)
.secret(CLIENT_SECRET)
.authority(AUTHORITY) // "https://login.microsoftonline.com/{YOUR_TENANT_ID}";
.scopes(SCOPES); // "https://redis.azure.com/.default";
credentialsSP = TokenBasedRedisCredentialsProvider.create(builder.build());
}
You can test the credentials provider by obtaining a token.
// Test Entra ID credentials provider can resolve credentials
RedisCredentials c = credentialsSP.resolveCredentialsAsync().toCompletableFuture().join();
System.out.println(c.getUsername());
Step 3 - Enable automatic re-authentication¶
Microsoft Entra ID tokens have a limited lifetime. Lettuce provides a mechanism to automatically re-authenticate when new credentials are emitted by a credentials provider.
// Enable automatic re-authentication
ClientOptions clientOptions = ClientOptions.builder()
.reauthenticateBehavior(ClientOptions.ReauthenticateBehavior.ON_NEW_CREDENTIALS)
.build();
Step 4 - Connect with Entra ID enabled credentials provider¶
// Use Entra ID credentials provider
RedisURI redisURI = RedisURI.builder()
.withHost(HOST)
.withPort(PORT)
.withSsl(true)
.withAuthentication(credentialsSP).build();
// RedisClient
RedisClient redisClient = RedisClient.create(redisURI);
redisClient.setOptions(clientOptions);
try {
redisClient.setOptions(clientOptions);
// Connect with Entra ID credentials provider
try (StatefulRedisConnection<String, String> user1 = redisClient.connect(StringCodec.UTF8)) {
System.out.println("Connected to redis as :" + user1.sync().aclWhoami());
System.out.println("Db size :" + user1.sync().dbsize());
}
} finally {
redisClient.shutdown(); // Shutdown Redis client and close connections
credentialsSP.close(); // Shutdown Entra ID Credentials provider
}