Java with Redis
Java has several Redis clients. This lesson covers using Jedis and Lettuce.
Redis Java Clients
Mainstream Java Redis clients:
- Jedis: lightweight, simple to use, based on blocking I/O
- Lettuce: built on Netty, supports async, thread-safe
- Redisson: distributed locks, distributed collections, and other advanced features
💡 Choice: Use Jedis for simple scenarios, Lettuce for high-performance scenarios, and Redisson for distributed scenarios.
Jedis
Adding Dependencies
Maven:
XML
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version>
</dependency>
Gradle:
GRADLE
implementation 'redis.clients:jedis:5.1.0'
Basic Connection
JAVA
import redis.clients.jedis.Jedis;
public class RedisDemo {
public static void main(String[] args) {
// Connect to Redis
Jedis jedis = new Jedis("localhost", 6379);
// Test connection
System.out.println(jedis.ping()); // PONG
// Close connection
jedis.close();
}
}
Connecting with Password
JAVA
Jedis jedis = new Jedis("localhost", 6379);
jedis.auth("your_password");
String Operations
JAVA
import redis.clients.jedis.Jedis;
Jedis jedis = new Jedis("localhost", 6379);
// SET and GET
jedis.set("name", "Alice");
String name = jedis.get("name"); // "Alice"
// SET with expiration
jedis.setex("session", 3600, "data"); // Expires after 1 hour
// MSET and MGET
jedis.mset("key1", "value1", "key2", "value2");
List<String> values = jedis.mget("key1", "key2");
// INCR
jedis.set("counter", "0");
Long count = jedis.incr("counter"); // 1
// DEL
jedis.del("name");
Hash Operations
JAVA
Jedis jedis = new Jedis("localhost", 6379);
// HSET and HGET
jedis.hset("user:1", "name", "Alice");
jedis.hset("user:1", "age", "25");
String name = jedis.hget("user:1", "name"); // "Alice"
// HMSET and HMGET
Map<String, String> user = new HashMap<>();
user.put("name", "Bob");
user.put("age", "30");
jedis.hset("user:2", user);
List<String> values = jedis.hmget("user:2", "name", "age");
// HGETALL
Map<String, String> allFields = jedis.hgetAll("user:2");
// HDEL
jedis.hdel("user:2", "age");
List Operations
JAVA
Jedis jedis = new Jedis("localhost", 6379);
// LPUSH and RPUSH
jedis.lpush("mylist", "value1", "value2");
jedis.rpush("mylist", "value3");
// LRANGE
List<String> list = jedis.lrange("mylist", 0, -1);
// LPOP and RPOP
String value = jedis.lpop("mylist");
String value2 = jedis.rpop("mylist");
// LLEN
long length = jedis.llen("mylist");
Set Operations
JAVA
Jedis jedis = new Jedis("localhost", 6379);
// SADD
jedis.sadd("myset", "a", "b", "c");
// SMEMBERS
Set<String> members = jedis.smembers("myset");
// SISMEMBER
boolean exists = jedis.sismember("myset", "a"); // true
// SREM
jedis.srem("myset", "a");
// SINTER, SUNION, SDIFF
jedis.sadd("set1", "a", "b", "c");
jedis.sadd("set2", "b", "c", "d");
Set<String> inter = jedis.sinter("set1", "set2"); // [b, c]
Sorted Set Operations
JAVA
Jedis jedis = new Jedis("localhost", 6379);
// ZADD
Map<String, Double> scores = new HashMap<>();
scores.put("player1", 100.0);
scores.put("player2", 200.0);
jedis.zadd("leaderboard", scores);
// ZRANGE
Set<String> top = jedis.zrange("leaderboard", 0, 9);
// ZRANGE WITHSCORES
Set<Tuple> topWithScores = jedis.zrangeWithScores("leaderboard", 0, 9);
// ZSCORE
Double score = jedis.zscore("leaderboard", "player1");
// ZINCRBY
jedis.zincrby("leaderboard", 50.0, "player1");
Jedis Connection Pool
JAVA
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisPool {
private static JedisPool pool;
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(100); // Max connections
config.setMaxIdle(50); // Max idle connections
config.setMinIdle(10); // Min idle connections
config.setTestOnBorrow(true); // Test on borrow
pool = new JedisPool(config, "localhost", 6379);
}
public static Jedis getJedis() {
return pool.getResource();
}
public static void close() {
pool.close();
}
}
// Using the connection pool
try (Jedis jedis = RedisPool.getJedis()) {
jedis.set("key", "value");
String value = jedis.get("key");
}
Jedis Pipelining
JAVA
Jedis jedis = new Jedis("localhost", 6379);
Pipeline pipeline = jedis.pipelined();
pipeline.set("key1", "value1");
pipeline.set("key2", "value2");
pipeline.set("key3", "value3");
pipeline.get("key1");
List<Object> results = pipeline.syncAndReturnAll();
Jedis Transactions
JAVA
Jedis jedis = new Jedis("localhost", 6379);
Transaction tx = jedis.multi();
tx.set("key1", "value1");
tx.set("key2", "value2");
tx.incr("counter");
List<Object> results = tx.exec();
Lettuce
Adding Dependencies
Maven:
XML
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.3.0</version>
</dependency>
Basic Connection
JAVA
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisConnection;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
public class LettuceDemo {
public static void main(String[] args) {
// Create client
RedisClient client = RedisClient.create("redis://localhost:6379");
// Create connection
StatefulRedisConnection<String, String> connection = client.connect();
// Get sync commands
RedisCommands<String, String> commands = connection.sync();
// Execute commands
commands.set("key", "value");
String value = commands.get("key");
// Close connection
connection.close();
client.shutdown();
}
}
Async Operations
JAVA
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
RedisClient client = RedisClient.create("redis://localhost:6379");
StatefulRedisConnection<String, String> connection = client.connect();
// Get async commands
RedisAsyncCommands<String, String> async = connection.async();
// Async SET
RedisFuture<String> future = async.set("key", "value");
// Wait for result
String result = future.get();
Lettuce Connection Pool
JAVA
import io.lettuce.core.RedisClient;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
ClientResources resources = DefaultClientResources.builder()
.ioThreadPoolSize(4)
.computationThreadPoolSize(4)
.build();
RedisClient client = RedisClient.create(resources, "redis://localhost:6379");
Spring Integration
Spring Boot Integration
Add dependency:
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Configuration:
YAML
# application.yml
spring:
redis:
host: localhost
port: 6379
password: your_password
database: 0
lettuce:
pool:
max-active: 100
max-idle: 50
min-idle: 10
Usage:
JAVA
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void delete(String key) {
redisTemplate.delete(key);
}
}
RedisTemplate Operations
JAVA
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// String operations
redisTemplate.opsForValue().set("key", "value");
Object value = redisTemplate.opsForValue().get("key");
// Hash operations
redisTemplate.opsForHash().put("user:1", "name", "Alice");
Object name = redisTemplate.opsForHash().get("user:1", "name");
// List operations
redisTemplate.opsForList().leftPush("mylist", "value1");
Object value = redisTemplate.opsForList().leftPop("mylist");
// Set operations
redisTemplate.opsForSet().add("myset", "a", "b", "c");
Set<Object> members = redisTemplate.opsForSet().members("myset");
// Sorted set operations
redisTemplate.opsForZSet().add("leaderboard", "player1", 100);
Set<Object> top = redisTemplate.opsForZSet().range("leaderboard", 0, 9);
Practical Examples
Example 1: Distributed Lock (Jedis)
JAVA
import redis.clients.jedis.Jedis;
import java.util.UUID;
public class DistributedLock {
private Jedis jedis;
private String lockKey;
private String identifier;
private int expireTime;
public DistributedLock(Jedis jedis, String lockKey, int expireTime) {
this.jedis = jedis;
this.lockKey = lockKey;
this.expireTime = expireTime;
this.identifier = UUID.randomUUID().toString();
}
public boolean acquire() {
String result = jedis.set(lockKey, identifier, "NX", "EX", expireTime);
return "OK".equals(result);
}
public boolean release() {
String script =
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
" return redis.call('del', KEYS[1]) " +
"else " +
" return 0 " +
"end";
Object result = jedis.eval(script, 1, lockKey, identifier);
return Long.valueOf(1).equals(result);
}
}
Example 2: Cache Utility
JAVA
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RedisCache {
private JedisPool pool;
private ObjectMapper mapper = new ObjectMapper();
public RedisCache(JedisPool pool) {
this.pool = pool;
}
public void set(String key, Object value, int expireSeconds) {
try (Jedis jedis = pool.getResource()) {
String json = mapper.writeValueAsString(value);
jedis.setex(key, expireSeconds, json);
} catch (Exception e) {
e.printStackTrace();
}
}
public <T> T get(String key, Class<T> clazz) {
try (Jedis jedis = pool.getResource()) {
String json = jedis.get(key);
if (json != null) {
return mapper.readValue(json, clazz);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
❓ FAQ
Q How do I choose between Jedis and Lettuce?
A Jedis is simple but not thread-safe. Lettuce is thread-safe and supports async. Lettuce is recommended.
Q Why does Jedis need a connection pool?
A Jedis is not thread-safe — each thread needs its own connection. A connection pool reuses connections for better performance.
Q Which client does Spring Boot use by default?
A Spring Boot 2.x uses Lettuce by default.
Q How do I handle Redis connection exceptions?
A Use try-with-resources to ensure connections are closed, and configure retry mechanisms.
Q How do I choose between RedisTemplate and Jedis?
A Use RedisTemplate for Spring projects, Jedis or Lettuce for non-Spring projects.
📖 Summary
- Jedis: simple to use, needs connection pool
- Lettuce: thread-safe, supports async, built on Netty
- Spring Boot integration: uses RedisTemplate
- Connection pools improve performance by reusing connections
- Practical examples: distributed lock, cache utility
📝 Exercises
- Basic operations: Use Jedis for string, hash, and list operations
- Connection pool: Configure a Jedis connection pool and test connection reuse
- Spring integration: Use RedisTemplate in a Spring Boot project
- Practical: Implement a simple distributed lock or cache utility
Next Lesson
In the next lesson, we will learn Node.js with Redis, covering Node.js Redis operations.



