13

There is a SpringBoot (v2.2.7) application, where a Redis cache is configured

fragment of pom.xml

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

When the Redis service is up and available, caching works as expected: results of methods annotated with @Cacheable are being cached. Unfortunately, when Redis service is not available any call to a cacheable method leads to an exception RedisConnectionFailureException: Unable to connect to Redis.

I guess it is reasonable if the application could work (execute business logic) independently from the cache availability.

Possible solutions are:

  1. custom implementation (i.e. a wrapper handling errors around the Redis cache)
  2. standard configuration in Spring considering Redis cache service health (if there is such thing)

What is the proper way to set up a fallback cache in SpringBoot?

1
  • 1
    Your best bet is going to be to create an implementation of CacheManager that delegates to RedisCacheManager, catches connection issues, and uses your secondary cache. However, as caching is supposed to speed things up, this may be less performant than just having no cache at all. The best solution is to solve the downtime issues with your redis cluster. Commented Mar 27 at 16:01

1 Answer 1

0

It can be done with the help of org.springframework.cache.interceptor.CacheErrorHandler

Out of the box you can use org.springframework.cache.interceptor.LoggingCacheErrorHandler implementation or make your own.

To register the CacheErrorHandler you configuration class must implement org.springframework.cache.annotation.CachingConfigurer interface.

See the following code excerpt as a reference

@Configuration
@EnableCaching
public class CacheConfiguration implements CachingConfigurer {

  @Override
  public CacheErrorHandler errorHandler() {
    return new LoggingCacheErrorHandler();
  }

  /*
  Just for reference.
   */
  @Bean
  public CacheManager cacheManager(LettuceConnectionFactory redisConnectionFactory) {
    return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory)
            .build();
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.