Redis from Spring Boot

Redis Course · lesson 13 of 19 · 5 min read

The starter gives you a template and a cache manager, and both have a default that surprises people.

Open this lesson in the learning hub

Key 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.host and spring.data.redis.port, from spring.redis.* in 2.x.
  • RedisTemplate defaults to JDK serialisation, so keys look like binary noise in redis-cli - use StringRedisTemplate or set serialisers.
  • @EnableCaching plus @Cacheable stores entries under cacheName::key through the auto-configured RedisCacheManager.
  • That cache manager has no default TTL, so set spring.cache.redis.time-to-live or your cache never expires anything.
  • Caching is proxy based: a method calling another @Cacheable method on this bypasses 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.