Spring @Cacheable redis异常不影响正常业务方案

 更新时间:2021年02月19日 08:36:58   作者:神农L  
这篇文章主要介绍了Spring @Cacheable redis异常不影响正常业务方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

背景

项目中,使用@Cacheable进行数据缓存。发现:当redis宕机之后,@Cacheable注解的方法并未进行缓存冲突,而是直接抛出异常。而这样的异常会导致服务不可用。

原因分析

我们是通过@EnableCaching进行缓存启用的,因此可以先看@EnableCaching的相关注释

通过@EnableCaching的类注释可发现,spring cache的核心配置接口为:org.springframework.cache.annotation.CachingConfigurer

/**
 * Interface to be implemented by @{@link org.springframework.context.annotation.Configuration
 * Configuration} classes annotated with @{@link EnableCaching} that wish or need to
 * specify explicitly how caches are resolved and how keys are generated for annotation-driven
 * cache management. Consider extending {@link CachingConfigurerSupport}, which provides a
 * stub implementation of all interface methods.
 *
 * <p>See @{@link EnableCaching} for general examples and context; see
 * {@link #cacheManager()}, {@link #cacheResolver()} and {@link #keyGenerator()}
 * for detailed instructions.
 *
 * @author Chris Beams
 * @author Stephane Nicoll
 * @since 3.1
 * @see EnableCaching
 * @see CachingConfigurerSupport
 */
public interface CachingConfigurer {

 /**
 * Return the cache manager bean to use for annotation-driven cache
 * management. A default {@link CacheResolver} will be initialized
 * behind the scenes with this cache manager. For more fine-grained
 * management of the cache resolution, consider setting the
 * {@link CacheResolver} directly.
 * <p>Implementations must explicitly declare
 * {@link org.springframework.context.annotation.Bean @Bean}, e.g.
 * <pre class="code">
 * Configuration
 * EnableCaching
 * public class AppConfig extends CachingConfigurerSupport {
 *  Bean // important!
 *  Override
 *  public CacheManager cacheManager() {
 *   // configure and return CacheManager instance
 *  }
 *  // ...
 * }
 * </pre>
 * See @{@link EnableCaching} for more complete examples.
 */
 CacheManager cacheManager();

 /**
 * Return the {@link CacheResolver} bean to use to resolve regular caches for
 * annotation-driven cache management. This is an alternative and more powerful
 * option of specifying the {@link CacheManager} to use.
 * <p>If both a {@link #cacheManager()} and {@code #cacheResolver()} are set,
 * the cache manager is ignored.
 * <p>Implementations must explicitly declare
 * {@link org.springframework.context.annotation.Bean @Bean}, e.g.
 * <pre class="code">
 * Configuration
 * EnableCaching
 * public class AppConfig extends CachingConfigurerSupport {
 *  Bean // important!
 *  Override
 *  public CacheResolver cacheResolver() {
 *   // configure and return CacheResolver instance
 *  }
 *  // ...
 * }
 * </pre>
 * See {@link EnableCaching} for more complete examples.
 */
 CacheResolver cacheResolver();

 /**
 * Return the key generator bean to use for annotation-driven cache management.
 * Implementations must explicitly declare
 * {@link org.springframework.context.annotation.Bean @Bean}, e.g.
 * <pre class="code">
 * Configuration
 * EnableCaching
 * public class AppConfig extends CachingConfigurerSupport {
 *  Bean // important!
 *  Override
 *  public KeyGenerator keyGenerator() {
 *   // configure and return KeyGenerator instance
 *  }
 *  // ...
 * }
 * </pre>
 * See @{@link EnableCaching} for more complete examples.
 */
 KeyGenerator keyGenerator();

 /**
 * Return the {@link CacheErrorHandler} to use to handle cache-related errors.
 * <p>By default,{@link org.springframework.cache.interceptor.SimpleCacheErrorHandler}
 * is used and simply throws the exception back at the client.
 * <p>Implementations must explicitly declare
 * {@link org.springframework.context.annotation.Bean @Bean}, e.g.
 * <pre class="code">
 * Configuration
 * EnableCaching
 * public class AppConfig extends CachingConfigurerSupport {
 *  Bean // important!
 *  Override
 *  public CacheErrorHandler errorHandler() {
 *   // configure and return CacheErrorHandler instance
 *  }
 *  // ...
 * }
 * </pre>
 * See @{@link EnableCaching} for more complete examples.
 */
 CacheErrorHandler errorHandler();

}

该接口errorHandler方法可配置异常的处理方式。通过该方法上的注释可以发现,默认的CacheErrorHandler实现类是org.springframework.cache.interceptor.SimpleCacheErrorHandler

/**
 * A simple {@link CacheErrorHandler} that does not handle the
 * exception at all, simply throwing it back at the client.
 *
 * @author Stephane Nicoll
 * @since 4.1
 */
public class SimpleCacheErrorHandler implements CacheErrorHandler {

 @Override
 public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
 throw exception;
 }

 @Override
 public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
 throw exception;
 }

 @Override
 public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
 throw exception;
 }

 @Override
 public void handleCacheClearError(RuntimeException exception, Cache cache) {
 throw exception;
 }
}

SimpleCacheErrorHandler类注释上说明的很清楚:对cache的异常不做任何处理,直接将该异常抛给客户端。因此默认的情况下,redis服务器异常后,直接就阻断了正常业务

解决方案

通过上面的分析可知,我们可以通过自定义CacheErrorHandler来干预@Cacheable的异常处理逻辑。具体代码如下:

public class RedisConfig extends CachingConfigurerSupport {

  /**
   * redis数据操作异常处理。该方法处理逻辑:在日志中打印出错误信息,但是放行。
   * 保证redis服务器出现连接等问题的时候不影响程序的正常运行
   */
  @Override
  public CacheErrorHandler errorHandler() {
    return new CacheErrorHandler() {
      @Override
      public void handleCachePutError(RuntimeException exception, Cache cache,
                      Object key, Object value) {
        handleRedisErrorException(exception, key);
      }

      @Override
      public void handleCacheGetError(RuntimeException exception, Cache cache,
                      Object key) {
        handleRedisErrorException(exception, key);
      }

      @Override
      public void handleCacheEvictError(RuntimeException exception, Cache cache,
                       Object key) {
        handleRedisErrorException(exception, key);
      }

      @Override
      public void handleCacheClearError(RuntimeException exception, Cache cache) {
        handleRedisErrorException(exception, null);
      }
    };
  }

  protected void handleRedisErrorException(RuntimeException exception, Object key) {
    log.error("redis异常:key=[{}]", key, exception);
  }
}

到此这篇关于Spring @Cacheable redis异常不影响正常业务方案的文章就介绍到这了,更多相关Spring @Cacheable redis异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Maven配置文件pom.xml详解

    Maven配置文件pom.xml详解

    什么是POM?这篇文章主要介绍了Maven的配置文件pom.xml,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • Java equals 方法与hashcode 方法的深入解析

    Java equals 方法与hashcode 方法的深入解析

    面试时经常会问起字符串比较相关的问题,比如:字符串比较时用的什么方法,内部实现如何?hashcode的作用,以及重写equal方法,为什么要重写hashcode方法?以下就为大家解答,需要的朋友可以参考下
    2013-07-07
  • Java中ShardingSphere分库分表实战

    Java中ShardingSphere分库分表实战

    我们做项目的时候,数据量比较大,单表千万级别的,需要分库分表,本文主要介绍了Java中ShardingSphere分库分表实战,感兴趣的可以了解一下
    2021-09-09
  • spring Bean的初始化过程解析

    spring Bean的初始化过程解析

    这篇文章主要介绍了spring Bean的初始化过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • Java排序之冒泡排序的实现与优化

    Java排序之冒泡排序的实现与优化

    冒泡排序是一种简单的交换排序。之所以叫做冒泡排序,因为我们可以把每个元素当成一个小气泡,根据气泡大小,一步一步移动到队伍的一端,最后形成一定对的顺序。本文将利用Java实现冒泡排序,并进行一定的优化,希望对大家有所帮助
    2022-11-11
  • JavaWeb三大组件之监听器Listener详解

    JavaWeb三大组件之监听器Listener详解

    这篇文章主要介绍了JavaWeb三大组件之监听器Listener详解,在JavaWeb应用程序中,Listener监听器是一种机制,用于监听和响应特定的事件,它可以感知并响应与应用程序相关的事件,从而执行相应的逻辑处理,需要的朋友可以参考下
    2023-10-10
  • Java 数组转List的四种方式小结

    Java 数组转List的四种方式小结

    本文主要介绍了四种将Java数组转换为List的方法,包括使用Arrays.asList、ArrayList构造器、Collections.addAll以及JDK8的Stream,具有一定的参考价值,感兴趣的可以了解一下
    2024-10-10
  • Spring和SpringMVC扫描注解类冲突的解决方案

    Spring和SpringMVC扫描注解类冲突的解决方案

    这篇文章主要介绍了Spring和SpringMVC扫描注解类冲突的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • java设计简单学生管理系统

    java设计简单学生管理系统

    这篇文章主要为大家详细介绍了java设计简单学生管理系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-09-09
  • Spring Boot ActiveMQ连接池配置过程解析

    Spring Boot ActiveMQ连接池配置过程解析

    这篇文章主要介绍了Spring Boot ActiveMQ连接池配置过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07

最新评论