Differences Among Jedis, Redisson, and Lettuce and Their Integration with Spring Boot
This article compares the Java Redis clients Jedis, Redisson, and Lettuce, explains their core differences, and provides detailed Spring Boot configuration and code examples for using each client, including RedisTemplate, RedissonClient, and annotation‑based caching.
1. Overview of Jedis, Redisson, and Lettuce
All three libraries provide Java APIs for interacting with Redis, but they differ in implementation details, feature sets, and concurrency models.
1.1 Jedis
Jedis is a straightforward Redis client that supports basic data types (String, Hash, List, Set, Sorted Set). It uses blocking I/O, so method calls are synchronous and the client instance is not thread‑safe; a connection pool is required for multi‑threaded use.
1.2 Redisson
Redisson adds high‑level distributed structures such as locks, collections, and delayed queues on top of Redis, making it suitable for complex coordination tasks.
1.3 Lettuce
Lettuce is built on Netty and provides an asynchronous, thread‑safe API that supports clustering, Sentinel, pipelining, and custom codecs.
2. Using Jedis
Basic Maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Example configuration (application‑dev.yml):
spring:
redis:
host: 192.168.1.140
port: 6379
database: 153. Spring Data RedisTemplate
Configuration snippet for Maven and YAML, followed by a typical usage example that caches a CustomersEntity in a hash:
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public CustomersEntity findById(Integer id) {
try {
String cached = stringRedisTemplate.opsForHash().get(REDIS_CUSTOMERS_ONE, id + "").toString();
if (cached != null) {
return JSONUtil.toBean(cached, CustomersEntity.class);
}
} catch (Exception e) { e.printStackTrace(); }
// fallback to DB and cache result
Optional
opt = customerRepo.findById(id);
if (opt.isPresent()) {
CustomersEntity entity = opt.get();
try { stringRedisTemplate.opsForHash().put(REDIS_CUSTOMERS_ONE, id + "", JSONUtil.toJsonStr(entity)); } catch (Exception e) { e.printStackTrace(); }
return entity;
}
return null;
}RedisTemplate API summary (hash, list, set, value, ZSet) is shown with illustrative images in the original article.
4. RedissonClient Usage
4.1 Basic Configuration
Maven dependencies:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.8.2</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>LATEST</version>
</dependency>YAML configuration (redisson-config.yml) defines a single server, connection pool sizes, timeouts, and a JSON codec:
# Redisson configuration
singleServerConfig:
address: "redis://192.168.1.140:6379"
database: 15
idleConnectionTimeout: 10000
pingTimeout: 1000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
connectionPoolSize: 64
threads: 0
nettyThreads: 0
codec:
class: "org.redisson.codec.JsonJacksonCodec"
transportMode: "NIO"Java configuration class to load the YAML:
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redisson() throws IOException {
Config config = Config.fromYAML(RedissonConfig.class.getClassLoader().getResource("redisson-config.yml"));
return Redisson.create(config);
}
}4.2 Sample Controller
REST endpoints demonstrate basic string operations, hash storage, key enumeration, and distributed lock usage using Redisson's RBucket , RMap , RAtomicLong , and lock primitives.
@RestController
@RequestMapping("/")
public class TeController {
@Autowired
private RedissonClient redissonClient;
@GetMapping("/set/{key}")
public String set(@PathVariable String key) {
RBucket
bucket = redissonClient.getBucket(key);
bucket.set(key + "1-v1");
return key;
}
@GetMapping("/get/{key}")
public String get(@PathVariable String key) {
RBucket
bucket = redissonClient.getBucket(key);
return bucket.get();
}
// Additional endpoints for hash, lock, atomic counter omitted for brevity
}4.3 Advanced Features
Redisson provides a rich set of distributed synchronization primitives: Lock, FairLock, MultiLock, RedLock, ReadWriteLock, Semaphore, PermitExpirableSemaphore, CountDownLatch, etc.
5. Annotation‑Based Redis Caching
Spring Cache can be enabled with @EnableCaching and configured to use Redis with custom serializers (StringRedisSerializer for keys, Jackson2JsonRedisSerializer for values). Example cache manager bean:
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer
keySer = new StringRedisSerializer();
Jackson2JsonRedisSerializer
valSer = new Jackson2JsonRedisSerializer<>(Object.class);
// configure ObjectMapper for JSON handling
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
valSer.setObjectMapper(om);
RedisCacheConfiguration cfg = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valSer))
.disableCachingNullValues();
return RedisCacheManager.builder(factory).cacheDefaults(cfg).build();
}Service methods can then use @Cacheable , @CachePut , and @CacheEvict to manage cached entities, with examples showing caching of single objects, lists, and custom key generation.
Conclusion
The article provides a comprehensive comparison of three popular Redis Java clients, detailed Spring Boot integration steps, and practical code samples for both low‑level operations and high‑level distributed features, making it a valuable reference for backend developers working with Redis.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.