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

java.net.ConnectException: Connection refused: connect

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

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

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
# Redis服务器地址

spring.redis.host=192.168.2.2
# Redis服务器连接端口
spring.redis.port=6379
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接超时时间(毫秒)
spring.redis.timeout=1000
package org.springframework.cache.annotation;

import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator; /**
* An implementation of {@link CachingConfigurer} with empty methods allowing
* sub-classes to override only the methods they're interested in.
*
* @author Stephane Nicoll
* @since 4.1
* @see CachingConfigurer
*/
public class CachingConfigurerSupport implements CachingConfigurer { @Override
public CacheManager cacheManager() {
return null;
} @Override
public KeyGenerator keyGenerator() {
return null;
} @Override
public CacheResolver cacheResolver() {
return null;
} @Override
public CacheErrorHandler errorHandler() {
return null;
} }
package com.gxkj.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import java.lang.reflect.Method; /**
* Created by yangqj on 2017/4/30.
*/
@Configuration
@EnableCaching
@EnableAspectJAutoProxy(exposeProxy = true)
@Slf4j
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host; @Value("${spring.redis.port}")
private int port; @Value("${spring.redis.timeout}")
private int timeout; @Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle; @Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis; @Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append("-");
sb.append(method.getName());
sb.append("-");
for (Object param : params) {
sb.append(param.toString());
}
return sb.toString();
}
};
} /**
* 设置@cacheable 序列化方式
*
* @return
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
return configuration;
} @Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory); // key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
// 所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
// 或者JdkSerializationRedisSerializer序列化方式;
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate;
} @Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory); template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return template;
} /**
* redis数据操作异常处理 这里的处理:在日志中打印出错误信息,但是放行
* 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
*
* @return
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() { @Override
public void handleCachePutError(RuntimeException exception, Cache cache,
Object key, Object value) {
RedisErrorException(exception, key);
} @Override
public void handleCacheGetError(RuntimeException exception, Cache cache,
Object key) {
RedisErrorException(exception, key);
} @Override
public void handleCacheEvictError(RuntimeException exception, Cache cache,
Object key) {
RedisErrorException(exception, key);
} @Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
RedisErrorException(exception, null);
}
};
return cacheErrorHandler;
} protected void RedisErrorException(Exception exception,Object key){
log.error("redis异常:key=[{}]", key, exception);
} }

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. R12_专题知识总结提炼-AP模块

    应付模块业务操作流程 供应商管理 供应商概述 在您使用 Oracle Purchasing 之前,需要定义供应商.供应商site,以及供应商联系人,  供应商主数据(SUPPLIER MASTER D ...

  2. Oracle EBS 采购 接收入库 接口开发

    http://blog.itpub.net/25164132/viewspace-746657/ 接收入库是项目中会经常碰到的开发,这类开发一般来说比较简单,但是接收入库在Oracle中其实涉及到很多 ...

  3. JAVA 从头开始<二>

    一.JAVA_HOME 1.环境变量如果经常变更,就要经常操作到Path,可能会一不小心把什么东西给删了 2.最好新建一个环境变量 3.如果使用新环境变量 ①原来的写法 ②现在的写法 新建环境变量JA ...

  4. ASP.NET中数据绑定表达式

    今天谈下.NET中的数据绑定表达式.数据绑定表达式必须包含在<%#和%>字符之间.格式如下: <tagprefix:tagname property='<%# data-bin ...

  5. 记录FormsAuthentication的使用方法

    配置,配置mode="Forms",其他属性详见 MSDN(点我直接查看各authentication属性) . <configuration> <system. ...

  6. [TJOI2013]攻击装置(网络流,最小割)

    前言 网络流被hbx吊起来打 Solution 考虑一下这个走法是不是和象棋中马的走法一模一样(废话) 那么显然我每一次移动是走三次,如果将棋盘二分图染色一下,不就是每一次只能走到另一个颜色的吗? 然 ...

  7. AJPFX告诉你MT4平台有什么优势?

    FX TERMINAL(Meta Trader4)交易平台功能 成功驾驭金融市场的第一步是拥有正确的工具.AJPFX为客户提供二十四小时的在线交易服务,MT4交易软件是目前全世界上最为先进,应用最为广 ...

  8. centos7 虚拟机中,网卡不启动的解决方式

    使用NAT模式的虚拟centos, 只显示两个网卡,无法连接外网, 输入systemctl start network后报错信息" Restarting network (via syste ...

  9. java之JIT(Just in time)

    Java程序最初是通过解释器进行解释执行的,当虚拟机发现某个方法或代码块运行的特别频繁时,会把这些代码认定为“热点代码”(Hot Spot Code).为了提高热点代码的执行效率,在运行时,虚拟机会把 ...

  10. poj1017----模拟

    题目大意: 现有1*1,2*2,3*3,4*4,5*5,6*6规格的产品若干个(高度都为h),问最少需要多少个 6*6*h的箱子把这些产品都装完 输入:每组测试数据共6个整数,分别代表1*1,...6 ...