Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 42 ยท Working with Redis

Redis with Spring Boot, RedisTemplate and @Cacheable

Use Redis from Spring Boot: Spring Data Redis, RedisTemplate and serializers, @Cacheable, @CachePut and @CacheEvict, cache TTLs, @RedisHash repositories and pub/sub.

Spring Boot makes Redis feel like part of the framework. Add one starter, set a host name, and you get a connection factory, two ready-made template beans and, with one annotation, a cache that sits behind your service methods. This lesson explains what each piece does so the configuration is not magic.

Redis cannot run inside this web page and the Spring libraries cannot either, so the Spring and Java code appears as read-only blocks. The runnable examples are JavaScript models that reproduce the behaviour that matters: how cache annotations decide between a hit and a miss, and how the choice of serializer shapes what is stored in Redis. For the other languages see Using Redis from Node.js, Python, PHP and Java.

Spring property names and defaults change between versions. The names below are for Spring Boot 3 and later (spring.data.redis.*); check the reference documentation of your version.

Setup

Add the starter and point it at a server:

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
PROPERTIES
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.timeout=2s
spring.data.redis.lettuce.pool.max-active=8

Boot configures a Lettuce connection factory (the multiplexing client described in the drivers lesson) and creates two beans: StringRedisTemplate and RedisTemplate<Object, Object>. Pooling needs commons-pool2 on the classpath; without it Lettuce shares a single connection, which is usually what you want.

RedisTemplate and serializers

RedisTemplate is Spring's typed, thread-safe wrapper over Redis commands. It groups them by data type through "operations" objects:

Java
@Service
class ProfileStore {
    private final StringRedisTemplate redis;

    ProfileStore(StringRedisTemplate redis) { this.redis = redis; }

    void remember(String userId, String name) {
        redis.opsForValue().set("profile:" + userId, name, Duration.ofMinutes(30));   // SET ... EX
        redis.opsForHash().put("profile:" + userId + ":meta", "lang", "en");          // HSET
        redis.opsForZSet().incrementScore("visits", userId, 1);                        // ZINCRBY
        redis.opsForList().leftPush("recent", userId);                                 // LPUSH
    }

    String find(String userId) {
        return redis.opsForValue().get("profile:" + userId);                           // GET
    }
}

The method names mirror the commands you already know (opsForValue for strings, opsForHash for hashes, opsForSet, opsForZSet, opsForList, opsForStream).

The important setting is the serializer, which turns keys and values into bytes. The generic RedisTemplate defaults to JDK serialization, so a String key "user:1" is stored as binary text with a class header (\xac\xed\x00\x05t\x00\x06user:1). You cannot read those keys with redis-cli, other languages cannot decode them, and renaming a class breaks old data. StringRedisTemplate stores plain UTF-8 strings, which is why it is the better default. For objects, configure a JSON serializer:

Java
@Bean
RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    var template = new RedisTemplate<String, Object>();
    template.setConnectionFactory(factory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(RedisSerializer.json());
    template.setHashValueSerializer(RedisSerializer.json());
    return template;
}

JSON is readable, language-neutral and survives refactoring better. Spring's JSON serializers can include a @class type hint so they can rebuild the right Java type; know what that does to key size, and avoid deserializing untrusted data with polymorphic types.

The first model shows the three storage choices side by side.

JS What each serializer puts in Redis

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Caching with annotations

The most popular use of Redis in Spring is the cache abstraction: you annotate a method, and Spring wraps it in a proxy that checks the cache first. Turn it on and choose Redis as the store:

Java
@SpringBootApplication
@EnableCaching
public class ShopApplication { /* ... */ }
PROPERTIES
spring.cache.type=redis
spring.cache.redis.time-to-live=10m
spring.cache.redis.key-prefix=shop:
spring.cache.redis.cache-null-values=false

Then annotate service methods:

Java
@Service
class ProductService {
    @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
    Product find(long id) { return repository.findById(id).orElse(null); }

    @CachePut(cacheNames = "products", key = "#product.id")
    Product update(Product product) { return repository.save(product); }

    @CacheEvict(cacheNames = "products", key = "#id")
    void delete(long id) { repository.deleteById(id); }

    @CacheEvict(cacheNames = "products", allEntries = true)
    void clearAll() { }
}
  • @Cacheable runs the method only on a miss, then stores the result. A hit returns the cached value and the method body never runs.
  • @CachePut always runs the method and writes the result, keeping the cache fresh after an update.
  • @CacheEvict removes one entry (or all of them with allEntries = true), the invalidation half of cache-aside.
  • key is a SpEL expression over the arguments, unless can veto caching a result, and condition can skip the cache for some calls.

Spring Data Redis stores the entry under the key cacheName::key by default (products::42, or shop:products::42 with a prefix). Clearing a whole cache deletes every key that starts with that prefix, so keep cache names distinct and never share a prefix between caches.

Per-cache lifetimes and serializers need a RedisCacheManager:

Java
@Bean
RedisCacheManager cacheManager(RedisConnectionFactory factory) {
    var base = RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(10))
        .disableCachingNullValues()
        .serializeValuesWith(SerializationPair.fromSerializer(RedisSerializer.json()));

    return RedisCacheManager.builder(factory)
        .cacheDefaults(base)
        .withCacheConfiguration("sessions", base.entryTtl(Duration.ofHours(1)))
        .withCacheConfiguration("rates", base.entryTtl(Duration.ofSeconds(30)))
        .build();
}

Three habits keep this healthy:

  1. Always set a TTL. The default has none, so entries stay until evicted. A TTL bounds staleness and memory (see eviction and memory).
  2. Cache values that serialize cleanly. Entities with lazy collections or cyclic references make poor cache values; cache a plain record or DTO.
  3. Beware of self-invocation. Annotations work through a proxy, so calling a @Cacheable method from another method in the same class skips the cache. Move it to another bean.

Cache stampedes (many misses at once on a hot key) are discussed in cache invalidation and stampedes; @Cacheable(sync = true) makes Spring let only one thread compute a missing value per key within a JVM.

The model below mimics the three annotations with a fake clock. It shows when the method body runs, how unless and TTLs behave, and the cacheName::key layout.

JS @Cacheable, @CachePut and @CacheEvict, modeled

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The database was read five times for seven find calls. The missing product was not cached because of unless, so each call for it reaches the database again; that is a deliberate trade-off, and a protection against caching null forever.

Spring Data repositories

For small, self-contained objects you can skip the cache layer and use a repository that stores the object as a Redis hash:

Java
@RedisHash(value = "session", timeToLive = 1800)
class UserSession {
    @Id String id;
    @Indexed String userId;      // creates a secondary index set so you can query by userId
    String device;
}

interface UserSessionRepository extends CrudRepository<UserSession, String> {
    List<UserSession> findByUserId(String userId);
}

save() writes a hash session:<id> plus helper sets for the index. timeToLive gives the entity an expiry. This suits sessions and similar short-lived records; for anything with joins or heavy querying, keep a database as the source of truth.

Pub/sub in Spring

Pub/sub works with a listener container that owns a dedicated subscribing connection:

Java
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory factory, NotificationListener listener) {
    var container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);
    container.addMessageListener(listener, new ChannelTopic("notifications"));
    return container;
}

@Component
class NotificationListener implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("Received: " + new String(message.getBody(), StandardCharsets.UTF_8));
    }
}

// Publishing:
redis.convertAndSend("notifications", "order 42 shipped");

Pub/sub is fire-and-forget: a listener that is down misses messages. For work that must not be lost, use streams or a queue.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is StringRedisTemplate often a better default than a RedisTemplate with JDK serialization?

    JDK serialization writes a binary Java-specific format. Plain strings (or JSON) are readable, portable and easier to debug.
  2. 2. What does @Cacheable do when the key is already in the cache?

    @Cacheable runs the method only on a miss. @CachePut is the annotation that always runs the method.
  3. 3. A @Cacheable method is called from another method in the same class and the cache is never used. Why?

    Spring wraps the bean in a proxy. A call from inside the same object does not pass through the proxy, so the cache logic never runs.
  4. 4. How do you give different cache names different lifetimes?

    RedisCacheManager.builder(...).withCacheConfiguration(name, config) sets the TTL and serializers for each named cache.

Summary

  • spring-boot-starter-data-redis gives you a Lettuce connection factory plus StringRedisTemplate and RedisTemplate, whose opsFor... methods map to Redis commands.
  • Choose serializers on purpose: strings or JSON are readable and portable, JDK serialization is not.
  • @EnableCaching with spring.cache.type=redis turns @Cacheable, @CachePut and @CacheEvict into cache-aside; entries live under cacheName::key.
  • Always configure a TTL, cache plain objects, and remember that self-invocation skips the proxy.
  • @RedisHash repositories suit short-lived records, and a RedisMessageListenerContainer handles pub/sub.

Next, see the same ideas in Python in Redis Caching in Django and Flask.