1. Overview

In this short tutorial, we’ll look at how to configure Redis as the data store for Spring Boot cache.

Further reading:

Spring Boot and Caffeine Cache

Learn how to use Caffeine cache with Spring Boot

Using Multiple Cache Managers in Spring

Learn how we can enable multiple cache managers in our Spring Boot application.

Cache Eviction in Spring Boot

Learn how to invalidate caches with Spring Boot.

2. Dependencies

To get started, let’s add the spring-boot-starter-cache and spring-boot-starter-data-redis artifacts:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>3.1.5</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>3.1.5</version>
</dependency>

These add caching support and bring in all the required dependencies.

3. Configuration

By adding the above dependencies and the @EnableCaching annotation, Spring Boot will auto-configure a RedisCacheManager with default cache configuration. However, we can modify this configuration prior to cache manager initialization in a couple of useful ways.

First, let’s create a RedisCacheConfiguration bean:

@Bean
public RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
      .entryTtl(Duration.ofMinutes(60))
      .disableCachingNullValues()
      .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}

This gives us more control over the default configuration. For example, we can set the desired time-to-live (TTL) values and customize the default serialization strategy for in-flight cache creation.

In order to have full control over the caching setup, let’s register our own RedisCacheManagerBuilderCustomizer bean:

@Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
    return (builder) -> builder
      .withCacheConfiguration("itemCache",
        RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)))
      .withCacheConfiguration("customerCache",
        RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)));
}

Here we’ve used RedisCacheManagerBuilder along with RedisCacheConfiguration to configure TTL values of 10 and 5 minutes for itemCache and customerCache, respectively. This helps to further fine-tune the caching behavior on a per-cache basis including null values, key prefixes and binary serialization.

It’s worth mentioning that the default connection details for the Redis instance are localhost:6379. Redis configuration can be used to further tweak the low-level connection details along with the host and port.

4. Example

In our example, we have an ItemService component that retrieves item information from the database. In effect, this represents a potentially costly operation and a good candidate for caching.

First, let’s create the integration test for this component using an embedded Redis server:

@Import({ CacheConfig.class, ItemService.class})
@ExtendWith(SpringExtension.class)
@EnableCaching
@ImportAutoConfiguration(classes = { 
  CacheAutoConfiguration.class, 
  RedisAutoConfiguration.class 
})
class ItemServiceCachingIntegrationTest {

    @MockBean
    private ItemRepository mockItemRepository;

    @Autowired
    private ItemService itemService;

    @Autowired
    private CacheManager cacheManager;

    @Test
    void givenRedisCaching_whenFindItemById_thenItemReturnedFromCache() {
        Item anItem = new Item(AN_ID, A_DESCRIPTION);
        given(mockItemRepository.findById(AN_ID))
          .willReturn(Optional.of(anItem));

        Item itemCacheMiss = itemService.getItemForId(AN_ID);
        Item itemCacheHit = itemService.getItemForId(AN_ID);

        assertThat(itemCacheMiss).isEqualTo(anItem);
        assertThat(itemCacheHit).isEqualTo(anItem);

        verify(mockItemRepository, times(1)).findById(AN_ID);
        assertThat(itemFromCache()).isEqualTo(anItem);
    }
}

Here we create a test slice for the caching behavior and invoke the getItemForId twice. The first invocation should obtain the item from the repository, but the second invocation should return the item from the cache without invoking the repository.

Finally, let’s enable the caching behavior using Spring’s @Cacheable annotation:

@Cacheable(value = "itemCache")
public Item getItemForId(String id) {
    return itemRepository.findById(id)
      .orElseThrow(RuntimeException::new);
}

This applies the caching logic while relying on the Redis cache infrastructure that we’ve configured earlier. Further details about controlling properties and behaviors of the Spring caching abstraction, including data update and eviction, are covered in our Guide to Caching in Spring.

5. Conclusion

In this article, we’ve seen how to use Redis for Spring caching.

We first described how to auto-configure Redis caching with minimal configuration. Then we looked at how to further customize the caching behavior by registering configuration beans.

Finally, we created a sample use case to demonstrate this caching in practice.

As always, the full source code is available over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are closed on this article!