1

I've enabled Caching in my Spring Boot app and I use Redis to serve the purpose.

My Spring Configuration is:

@Configuration
@EnableCaching
@ConditionalOnProperty(
value = "spring.cache.enabled",
matchIfMissing = true)
public class CacheConfiguration {

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    return RedisCacheManager.builder(redisConnectionFactory)
        .cacheDefaults(buildDefault())
        .withInitialCacheConfigurations(buildFromSettings())
        .transactionAware()
        .build();
}

private Map<String, RedisCacheConfiguration> buildFromSettings() {
    return Arrays.stream(CacheSettings.values()).collect(Collectors.toMap(CacheSettings::getCacheName, this::buildFromSettings));
}

private RedisCacheConfiguration buildDefault() {
    return RedisCacheConfiguration.defaultCacheConfig()
        .prefixCacheNameWith(CacheSettings.DEFAULTS.getCacheName())
        .entryTtl(Duration.ofSeconds(CacheSettings.DEFAULTS.getTtl()));
}

private RedisCacheConfiguration buildFromSettings(CacheSettings cacheSettings) {
    return RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofSeconds(cacheSettings.getTtl()));
}

}

However, whenever any problems with Redis server happens, for example timeout exception occurs, the app stops working whereas I think it had better skip the Caching and go on with normal execution flow.

So, does anyone have any idea on how to do it in Spring Boot?

Here is the exception I got

org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException

I know, that I can simply extend CachingConfigurerSupport and only override the errorHandler() method, returning a custom CacheErrorHandler how to mentioned in this answer https://stackoverflow.com/a/68072419/1527469

But it works only if setting RedisCacheManager transactionAware to false as mentioned in this answer https://stackoverflow.com/a/66010262/5837557

So, my question is how to skip the Caching in Spring Boot with configuration settings RedisCacheManager transactionAware to true?

bobanman
  • 23
  • 7
  • You would also need to implement a circuit breaker, because otherwise you would still wait for a timeout in every operation. Even with a circuit breaker you might run out of resources, if the cache is not working. Not sure whether this will prove helpful. It will probably be counter productive since its masking random errors that need to be fixed. – cruftex Dec 07 '21 at 04:42
  • With respect to transactions: If your cache server gets offline and comes back and you just skip the updates, in case the cache is offline, your cache will be out of sync with the application. You either need to clear the cache or replay the missed updates before it is used again. – cruftex Dec 07 '21 at 04:49

0 Answers0