Redis from Spring Boot
The starter gives you a template and a cache manager, and both have a default that surprises people.
Open this lesson in the learning hubKey points
- Add
spring-boot-starter-data-redis; Lettuce is the client since Spring Boot 2.0 and Jedis is opt-in. - Spring Boot 3 renamed the properties to
spring.data.redis.hostandspring.data.redis.port, fromspring.redis.*in 2.x. RedisTemplatedefaults to JDK serialisation, so keys look like binary noise in redis-cli - useStringRedisTemplateor set serialisers.@EnableCachingplus@Cacheablestores entries undercacheName::keythrough the auto-configured RedisCacheManager.- That cache manager has no default TTL, so set
spring.cache.redis.time-to-liveor your cache never expires anything. - Caching is proxy based: a method calling another
@Cacheablemethod onthisbypasses the cache entirely.
Example
@Configuration
@EnableCaching
class RedisConfig {
@Bean
RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, Object> t = new RedisTemplate<>();
t.setConnectionFactory(cf);
t.setKeySerializer(new StringRedisSerializer()); // readable keys
t.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return t;
}
}
@Service
class ProductService {
@Cacheable(cacheNames = "product", key = "#id") // stored as product::991
Product find(long id) { return repo.findById(id).orElseThrow(); }
@CacheEvict(cacheNames = "product", key = "#p.id")
void update(Product p) { repo.save(p); }
}
// application.properties (Spring Boot 3)
// spring.data.redis.host=localhost
// spring.data.redis.port=6379
// spring.cache.redis.time-to-live=10m
// spring.cache.redis.cache-null-values=false
Set a TTL on the Redis cache manager and a real serialiser on the template - neither default is what you want.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Redis Course course, and every lesson in it is listed on the Redis Course contents page.