How to handle redis exceptions by using Spring Cache?

Viewed 1087

I am currently working on a project which incorporates both spring data redis and Spring Cache. In spring data redis, I am calling redis by using the redis template. I handle all of the exceptions thrown by the redis template in a try catch block as so:

   try{
       // execute some operation with redis template
    }
    catch(RedisCommandTimeoutException ex){

    }
    catch(RedisBusyException ex){

    }
    catch(RedisConnectionFailureException ex){

    }
    catch(Exception ex){

    }

Can I use a similar try-catch block to handle exceptions coming from @cacheable? how can I handle exceptions thrown by redis in cacheable?

1 Answers

I believe you want to define your own CacheErrorHandler which will handle @Cachable, @CachePut, and @CacheEvict.

You would define the CacheErrorHandler:

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.interceptor.CacheErrorHandler;

@Slf4j
public class CustomCacheErrorHandler implements CacheErrorHandler {
    @Override
    public void handleCacheGetError(RuntimeException e, Cache cache, Object o) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) {
        log.error(e.getMessage(), e);
    }

    @Override
    public void handleCacheClearError(RuntimeException e, Cache cache) {
        log.error(e.getMessage(), e);
    }
}

And then register it:

import org.springframework.cache.annotation.CachingConfigurerSupport;  
import org.springframework.cache.interceptor.CacheErrorHandler;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class CachingConfiguration extends CachingConfigurerSupport {  
    @Override
    public CacheErrorHandler errorHandler() {
        return new CustomCacheErrorHandler();
    }
}
Related