使用Cacheable注解Redis方法时,如果Redis服务器挂了,就直接抛出异常了,

java.net.ConnectException: Connection refused: connect

那么,有没有什么办法可以继续向下执行方法,从相关的数据库中查询数据,而不是直接抛出异常导致整个程序终止运行呢?

经过反复翻看Spring的源码和相关资料,并经过不断验证,得出了答案:有相关的方案!!!

原文:https://blog.csdn.net/l1028386804/article/details/82597154

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.4.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-data-redis</artifactId>
  9. </dependency>
  1. # Redis服务器地址
  2. spring.redis.host=192.168.2.2
  3. # Redis服务器连接端口
  4. spring.redis.port=6379
  5. # 连接池中的最大空闲连接
  6. spring.redis.jedis.pool.max-idle=8
  7. # 连接池中的最小空闲连接
  8. spring.redis.jedis.pool.min-idle=0
  9. # 连接池最大连接数(使用负值表示没有限制)
  10. spring.redis.jedis.pool.max-active=8
  11. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  12. spring.redis.jedis.pool.max-wait=-1
  13. # 连接超时时间(毫秒)
  14. spring.redis.timeout=1000
  1. package org.springframework.cache.annotation;
  2. import org.springframework.cache.CacheManager;
  3. import org.springframework.cache.interceptor.CacheErrorHandler;
  4. import org.springframework.cache.interceptor.CacheResolver;
  5. import org.springframework.cache.interceptor.KeyGenerator;
  6. /**
  7. * An implementation of {@link CachingConfigurer} with empty methods allowing
  8. * sub-classes to override only the methods they're interested in.
  9. *
  10. * @author Stephane Nicoll
  11. * @since 4.1
  12. * @see CachingConfigurer
  13. */
  14. public class CachingConfigurerSupport implements CachingConfigurer {
  15. @Override
  16. public CacheManager cacheManager() {
  17. return null;
  18. }
  19. @Override
  20. public KeyGenerator keyGenerator() {
  21. return null;
  22. }
  23. @Override
  24. public CacheResolver cacheResolver() {
  25. return null;
  26. }
  27. @Override
  28. public CacheErrorHandler errorHandler() {
  29. return null;
  30. }
  31. }
  1. package com.gxkj.config;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.cache.Cache;
  5. import org.springframework.cache.annotation.CachingConfigurerSupport;
  6. import org.springframework.cache.annotation.EnableCaching;
  7. import org.springframework.cache.interceptor.CacheErrorHandler;
  8. import org.springframework.cache.interceptor.KeyGenerator;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.context.annotation.EnableAspectJAutoProxy;
  12. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  13. import org.springframework.data.redis.connection.RedisConnectionFactory;
  14. import org.springframework.data.redis.core.RedisTemplate;
  15. import org.springframework.data.redis.core.StringRedisTemplate;
  16. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  17. import org.springframework.data.redis.serializer.RedisSerializationContext;
  18. import org.springframework.data.redis.serializer.RedisSerializer;
  19. import org.springframework.data.redis.serializer.StringRedisSerializer;
  20. import java.lang.reflect.Method;
  21. /**
  22. * Created by yangqj on 2017/4/30.
  23. */
  24. @Configuration
  25. @EnableCaching
  26. @EnableAspectJAutoProxy(exposeProxy = true)
  27. @Slf4j
  28. public class RedisConfig extends CachingConfigurerSupport {
  29. @Value("${spring.redis.host}")
  30. private String host;
  31. @Value("${spring.redis.port}")
  32. private int port;
  33. @Value("${spring.redis.timeout}")
  34. private int timeout;
  35. @Value("${spring.redis.jedis.pool.max-idle}")
  36. private int maxIdle;
  37. @Value("${spring.redis.jedis.pool.max-wait}")
  38. private long maxWaitMillis;
  39. @Bean
  40. public KeyGenerator keyGenerator() {
  41. return new KeyGenerator() {
  42. @Override
  43. public Object generate(Object o, Method method, Object... params) {
  44. StringBuilder sb = new StringBuilder();
  45. sb.append(o.getClass().getName());
  46. sb.append("-");
  47. sb.append(method.getName());
  48. sb.append("-");
  49. for (Object param : params) {
  50. sb.append(param.toString());
  51. }
  52. return sb.toString();
  53. }
  54. };
  55. }
  56. /**
  57. * 设置@cacheable 序列化方式
  58. *
  59. * @return
  60. */
  61. @Bean
  62. public RedisCacheConfiguration redisCacheConfiguration() {
  63. RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
  64. RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
  65. configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
  66. return configuration;
  67. }
  68. @Bean
  69. public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
  70. RedisTemplate redisTemplate = new RedisTemplate();
  71. redisTemplate.setConnectionFactory(factory);
  72. // key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
  73. // 所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
  74. // 或者JdkSerializationRedisSerializer序列化方式;
  75. redisTemplate.setKeySerializer(new StringRedisSerializer());
  76. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  77. redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  78. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  79. return redisTemplate;
  80. }
  81. @Bean
  82. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  83. StringRedisTemplate template = new StringRedisTemplate();
  84. template.setConnectionFactory(redisConnectionFactory);
  85. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  86. template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  87. return template;
  88. }
  89. /**
  90. * redis数据操作异常处理 这里的处理:在日志中打印出错误信息,但是放行
  91. * 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
  92. *
  93. * @return
  94. */
  95. @Bean
  96. @Override
  97. public CacheErrorHandler errorHandler() {
  98. CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
  99. @Override
  100. public void handleCachePutError(RuntimeException exception, Cache cache,
  101. Object key, Object value) {
  102. RedisErrorException(exception, key);
  103. }
  104. @Override
  105. public void handleCacheGetError(RuntimeException exception, Cache cache,
  106. Object key) {
  107. RedisErrorException(exception, key);
  108. }
  109. @Override
  110. public void handleCacheEvictError(RuntimeException exception, Cache cache,
  111. Object key) {
  112. RedisErrorException(exception, key);
  113. }
  114. @Override
  115. public void handleCacheClearError(RuntimeException exception, Cache cache) {
  116. RedisErrorException(exception, null);
  117. }
  118. };
  119. return cacheErrorHandler;
  120. }
  121. protected void RedisErrorException(Exception exception,Object key){
  122. log.error("redis异常:key=[{}]", key, exception);
  123. }
  124. }

Cacheable redis 宕机的更多相关文章

  1. Redis宕机的问题

    在主从模式下宕机要分为区分来看: slave从redis宕机 ​ 在Redis中从库重新启动后会自动加入到主从架构中,自动完成同步数据: ​ 如果从数据库实现了持久化,只要重新假如到主从架构中会实现增 ...

  2. redis宕机如何解决?如果是项目上线的宕机呢?

    我们先来了解一下  bridge网络模式 他会创建一个docker0桥,看完这个我们就会知道redis哨兵机制的端口了. 之后继续研究redis宕机的解决办法! 宕机: 服务器停止服务 如果只有一台r ...

  3. [转帖]Redis持久化--Redis宕机或者出现意外删库导致数据丢失--解决方案

    Redis持久化--Redis宕机或者出现意外删库导致数据丢失--解决方案 https://www.cnblogs.com/xlecho/p/11834011.html echo编辑整理,欢迎转载,转 ...

  4. Redis持久化--Redis宕机或者出现意外删库导致数据丢失--解决方案

    echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!!! Red ...

  5. Redis 日志篇:无畏宕机快速恢复的杀手锏

    特立独行是对的,融入圈子也是对的,重点是要想清楚自己向往怎样的生活,为此愿意付出怎样的代价. 我们通常将 Redis 作为缓存使用,提高读取响应性能,一旦 Redis 宕机,内存中的数据全部丢失,假如 ...

  6. redis宕机时哨兵的处理

    https://blog.csdn.net/a67474506/article/details/50435498 redis宕机是的故障处理 重启故障机 sentinel.conf 的配置会改变

  7. 由Redis的hGetAll函数所引发的一次服务宕机事件

    昨晚通宵生产压测,终于算是将生产服务宕机的原因定位到了,心累.这篇博客,算作一个复盘和记录吧... 先来看看Redis的缓存淘汰算法思维导图: 说明:当实际占用的内存超过Redis配置的maxmemo ...

  8. Redis的KEYS命令引起宕机事件

    摘要: 使用 Redis 的开发者必看,吸取教训啊! 原文:Redis 的 KEYS 命令引起 RDS 数据库雪崩,RDS 发生两次宕机,造成几百万的资金损失 作者:陈浩翔 Fundebug经授权转载 ...

  9. redis集群节点宕机

    redis集群是有很多个redis一起工作,那么就需要这个集群不是那么容易挂掉,所以呢,理论上就应该给集群中的每个节点至少一个备用的redis服务.这个备用的redis称为从节点(slave). 1. ...

随机推荐

  1. DevExpress中Tile Application窗体的模型架构图

    DEV中Tile Application模型架构比较复杂,整理一下和大家分享. 图中:立体代表类:虚线椭圆代表属性.

  2. (原创)PetaPoco使用小记(2014-5-5更新)

    接触PetaPoco已经有一段时间了,为了全面了解一下PetaPoco,刚好结合目前在做的一个项目,对常用的几个业务操作用PetaPoco进行改写,如增删改查.分页以及存储过程的调用,在文章的最后附上 ...

  3. AgentJob--无法重启Job--22022错误

    错误描述: 发现有个Job计划为长期重复运行,但从某个时间点后未运行,无任何错误信息. 手动启动该Job后爆以下错误 运行环境: Window Server 2008 R2 Enterprise Mi ...

  4. 【洛谷4719】 动态dp(树链剖分,dp,矩阵乘法)

    前言 其实我只是为了过掉模板而写的ddp,实际应用被吊着锤 Solution 并不想写详细的过程 一句话过程:将子树中轻儿子的贡献挂到这个点上面来 详细版:(引用yyb) 总结一下的话,大致的过程是这 ...

  5. QQ个人信息保护 | 攻的对面叫防

    近来我们愈来愈重视个人信息保护,当接到骚扰电话时,你心里或许在想(我手机号怎么又被别人知道的?别人是怎么知道我手机号的?),现在的时代,手机已或不可缺,QQ几乎每个人都在用.而有些人总想保护个人QQ资 ...

  6. [Dart]语法基础

    此页面向您展示如何使用每个主要Dart功能,从变量和运算符到类和库,假设您已经知道如何使用其他语言编程. 要了解有关Dart核心库的更多信息,请参阅 Dart Libraries之旅.无论何时需要有关 ...

  7. Python中线程与互斥锁

    了解之前我们先了解一下什么是多任务? 概念: 几个不同的事件在同时运行就是多任务, 这样的话, 我们有牵扯到了真的多任务, 假的多任务; 并行: 真的多任务, 通过电脑的核数来确定 并发: 假的多任务 ...

  8. servlet转发与重定向区别

    servlet转发与重定向   HttpServletRequest: 表示浏览器向服务器发送的请求报文,由Tomcat创建然后作为参数传递给我们doget,dopost方法. 功能:getParam ...

  9. Python Django 的学习资料

    十分有用的链接: 链接1:http://www.cnblogs.com/wupeiqi/articles/5433893.html   (银角大王) 链接2:https://www.cnblogs.c ...

  10. css四种选择器总结

    css 在网页开发中扮演着重要的角色,被誉为网页开发的三剑客,如果说html是人的外在器官部分,那css无疑是各个器官组成在一起然后表现出来,css又称样式重叠在网页排版布局中的地位举足轻重.   做 ...