Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

How to handle redis exceptions by using Spring Cache?

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?

question from:https://stackoverflow.com/questions/65853418/how-to-handle-redis-exceptions-by-using-spring-cache

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...