Differences Among Jedis, Redisson, and Lettuce and Their Usage in Spring Boot
This article compares the Java Redis clients Jedis, Redisson, and Lettuce, explains their distinct features and thread‑safety models, and provides detailed Spring Boot configuration and code examples for using RedisTemplate, RedissonClient, and annotation‑based caching to implement distributed locks, hash operations, and cache management.
1. Differences Among Jedis, Redisson, Lettuce
All three provide Java APIs for Redis, but differ in implementation and features. Jedis is a synchronous client using blocking I/O and is not thread‑safe without a connection pool. Redisson offers distributed locks, collections, and delayed queues. Lettuce is built on Netty, provides asynchronous, thread‑safe APIs, and supports clustering, Sentinel, pipelining, and codecs.
2. Jedis
3. RedisTemplate
3.1 Configuration
Maven dependency (add version if not inherited from parent):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>application-dev.yml example:
spring:
redis:
host: 192.168.1.140
port: 6379
password:
database: 153.2 Usage Example
@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();
}
Optional
byId = customerRepo.findById(id);
if (byId.isPresent()) {
CustomersEntity entity = byId.get();
try {
stringRedisTemplate.opsForHash().put(REDIS_CUSTOMERS_ONE, id + "", JSONUtil.toJsonStr(entity));
} catch (Exception e) {
e.printStackTrace();
}
return entity;
}
return null;
}3.3 Extension
Shows the Maven dependency tree for spring-boot-starter-data-redis and a partial list of StringRedisTemplate APIs (opsForHash, opsForList, opsForSet, opsForValue, opsForZSet).
4. RedissonClient Operations
4.1 Basic Configuration
4.1.1 Maven pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<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>4.1.2 Configuration File (YAML)
# Redisson configuration
singleServerConfig:
address: "redis://192.168.1.140:6379"
password: null
clientName: null
database: 15
idleConnectionTimeout: 10000
pingTimeout: 1000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
reconnectionTimeout: 3000
failedAttempts: 3
subscriptionsPerConnection: 5
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
connectionMinimumIdleSize: 32
connectionPoolSize: 64
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec:
class: "org.redisson.codec.JsonJacksonCodec"
transportMode: "NIO"4.1.3 Reading Configuration in Spring
@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 Usage Example
@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();
}
// hash operations, lock examples, atomic long decrement, etc.
}4.3 Extensions
Redisson provides a rich set of distributed primitives such as Lock, FairLock, MultiLock, RedLock, ReadWriteLock, Semaphore, PermitExpirableSemaphore, CountDownLatch, and more.
5. Annotation‑Based Redis Cache
5.1 Maven and YML Configuration
@EnableCaching
@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheConfig {
private Duration timeToLive = Duration.ZERO;
// getters and setters omitted
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer
keySerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer
valueSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
valueSerializer.setObjectMapper(om);
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer))
.disableCachingNullValues();
return RedisCacheManager.builder(factory).cacheDefaults(config).build();
}
}5.2 Usage Example
@Transactional
@Service
public class ReImpl implements RedisService {
@Resource
private CustomerRepo customerRepo;
@Resource
private StringRedisTemplate stringRedisTemplate;
public static final String REDIS_CUSTOMERS_ONE = "Customers";
public static final String REDIS_CUSTOMERS_ALL = "allList";
@Cacheable(value = "cache:customer", unless = "null == #result", key = "#id")
public CustomersEntity cacheOne(Integer id) {
return customerRepo.findById(id).orElse(null);
}
@CacheEvict(value = "cache:customer", key = "'cacheOne5'.' + #id")
public Object del(Integer id) { return null; }
@Cacheable(value = "cache:all")
public List
cacheList() {
return customerRepo.findAll();
}
@CachePut(value = "cache:all", unless = "null == #result", key = "#root.methodName")
public List
cacheList2() {
return customerRepo.findAll();
}
}5.3 Extension
Shows how Spring Cache annotations integrate with Redis to provide transparent caching, cache eviction, and cache updating for both single objects and collections.
The article also contains promotional messages for a “top‑architect” community, interview question packs, and various external links, but the core technical content provides practical guidance on using Redis clients in Java applications.
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.