Redis
suggest changeRedis is an open-source, in-memory data structure store used as a high-speed database, cache, message broker, and streaming engine. In Java applications, Redis is commonly used to cache expensive database queries, manage user sessions, coordinate distributed locks, and implement Pub/Sub messaging.
The two most widely used Java Redis client libraries are:
- Jedis: A lightweight, straightforward, synchronous client.
- Lettuce: A thread-safe, non-blocking client built on Netty that supports synchronous, asynchronous (
CompletableFuture), and reactive (Project Reactor) programming. Lettuce is also the default driver in Spring Boot.
1. Connecting with Jedis
Add the Jedis dependency to your pom.xml:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>8.0.2</version>
</dependency>
Connection Pooling with RedisClient
Because raw Jedis instances are not thread-safe, multi-threaded applications must use a connection pool. RedisClient (the replacement for the now-deprecated JedisPool) is thread-safe and manages a pool internally:
import redis.clients.jedis.ConnectionPoolConfig;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.RedisClient;
import redis.clients.jedis.params.SetParams;
public class JedisExample {
public static void main(String[] args) {
ConnectionPoolConfig poolConfig = new ConnectionPoolConfig();
poolConfig.setMaxTotal(32);
poolConfig.setMaxIdle(16);
poolConfig.setMinIdle(4);
poolConfig.setTestOnBorrow(true);
try (RedisClient redis = RedisClient.builder()
.hostAndPort("localhost", 6379)
.clientConfig(DefaultJedisClientConfig.builder().timeoutMillis(2000).build())
.poolConfig(poolConfig)
.build()) {
// Each command borrows a connection from the pool and returns it afterwards
// String operations with TTL
redis.set("session:user:101", "{\"username\":\"alice\",\"role\":\"admin\"}",
new SetParams().ex(3600));
String sessionData = redis.get("session:user:101");
System.out.println("Retrieved session: " + sessionData);
// Hash operations (ideal for objects)
String userKey = "user:101";
redis.hset(userKey, "name", "Alice");
redis.hset(userKey, "email", "alice@example.com");
redis.hincrBy(userKey, "login_count", 1);
String name = redis.hget(userKey, "name");
System.out.println("User name from Hash: " + name);
}
}
}
2. Asynchronous Operations with Lettuce
Add the Lettuce dependency to your pom.xml:
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>7.9.0.RELEASE</version>
</dependency>
Unlike a raw Jedis instance, a single StatefulRedisConnection in Lettuce is thread-safe and can be shared across multiple threads.
Async API with CompletableFuture
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
public class LettuceAsyncExample {
public static void main(String[] args) {
RedisURI redisURI = RedisURI.builder()
.withHost("localhost")
.withPort(6379)
.withTimeout(Duration.ofSeconds(5))
.build();
RedisClient client = RedisClient.create(redisURI);
try (StatefulRedisConnection<String, String> connection = client.connect()) {
RedisAsyncCommands<String, String> async = connection.async();
CompletableFuture<String> setFuture = async.set("config:rate_limit", "1000")
.toCompletableFuture();
setFuture.thenCompose(result -> async.get("config:rate_limit").toCompletableFuture())
.thenAccept(value -> System.out.println("Rate limit: " + value))
.join();
} finally {
client.shutdown();
}
}
}
3. Pipelining Commands
Pipelining batches multiple commands together and sends them in a single network round-trip without waiting for each individual response:
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.RedisClient;
import redis.clients.jedis.Response;
public class PipelineExample {
public static void batchInsert(RedisClient jedis) {
Pipeline pipeline = jedis.pipelined();
Response<String> r1 = pipeline.set("counter:a", "1");
Response<Long> r2 = pipeline.incr("counter:a");
Response<Long> r3 = pipeline.rpush("queue:tasks", "task-1", "task-2", "task-3");
// Execute all queued commands at once
pipeline.sync();
System.out.println("New counter value: " + r2.get());
System.out.println("Queue size: " + r3.get());
}
}
4. Pub/Sub Messaging
Redis provides high-performance Publish/Subscribe channels for decoupled event broadcasting:
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.RedisClient;
public class RedisPubSubExample {
public static void subscribe(RedisClient jedis, String channel) {
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
System.out.printf("Received message on [%s]: %s%n", channel, message);
}
}, channel);
}
public static void publish(RedisClient jedis, String channel, String message) {
jedis.publish(channel, message);
}
}
5. Best Practices
- Resource Cleanup: Always close connections and pools using try-with-resources or framework shutdown hooks.
- Key Namespacing: Use structured colon-delimited naming conventions (e.g.,
app:environment:entity:id) to prevent collisions across services. - Appropriate TTLs: Always attach TTL expiration (
EXPIREorSETEX) to temporary cache entries to prevent unbounded memory growth. - Avoid Expensive Commands in Production: Commands like
KEYS *block the single-threaded Redis engine. UseSCANinstead when iterating across keys.