如何解决如何在Spring Boot中防止Redis服务器等外部连接失败时快速失败?
是否有一种方法可以防止spring-boot
应用程序由于外部连接故障而在启动时失败?我发现other similar questions建议使用@Lazy
批注来防止@Configuration
bean初始化,但是对于使用Spring Data Redis
客户端的Jedis
,此解决方案不适用于我。
此外,诸如this之类的其他解决方案特定于应用程序中使用的依赖项。例如,Spring Cloud
具有以下属性来控制故障转移行为-
spring.cloud.config.fail-fast=true
您可以通过关闭redis
服务器来使用我为问题创建的this project。
下面是我的代码的样子-
@Lazy
@Configuration
public class RedisConfiguration {
@Value("${spring.redis.sentinel.master}")
private String SENTINEL_MASTER;
@Value("${spring.redis.sentinel.nodes}")
private String SENTINEL_NODES;
@Value("${spring.redis.security.enabled:false}")
private boolean REDIS_SECURITY_ENABLED;
@Value("${spring.redis.security.password:}")
private String REDIS_PASSWORD;
@Lazy
@Bean // somehow this always gets initialized
public RedisConnectionFactory jedisConnectionFactory() {
// create set of sentinel nodes
System.out.println(SENTINEL_NODES);
Set<String> sentinelNodesSet = new HashSet<>(5);
StringTokenizer st = new StringTokenizer(SENTINEL_NODES,",");
while (st.hasMoreTokens())
sentinelNodesSet.add(st.nextToken());
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(SENTINEL_MASTER,sentinelNodesSet);
if (REDIS_SECURITY_ENABLED) {
sentinelConfig.setPassword(REDIS_PASSWORD);
}
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig);
return jedisConnectionFactory;
}
下面是异常跟踪-
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建类中定义的名称为'stringRedisTemplate'的bean时出错 路径资源 [org / springframework / boot / autoconfigure / data / redis / RedisAutoConfiguration.class]: 通过方法'stringRedisTemplate'表示的不满意依赖性 参数0;嵌套异常为 org.springframework.beans.factory.BeanCreationException:错误 创建在类路径中定义的名称为“ jedisConnectionFactory”的bean 资源[com / springboot / redisintegration / RedisConfiguration.class]: 调用init方法失败;嵌套异常为 redis.clients.jedis.exceptions.JedisConnectionException:所有标记 下来,无法确定mysentinel主服务器在哪里运行... org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:538) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0(AbstractBeanFactory.java:324) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) 〜[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) 〜[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.boot.SpringApplication.run(SpringApplication.java:315) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) 〜[spring-boot-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 com.springboot.redisintegration.RedisIntegrationApplication.main(RedisIntegrationApplication.java:21) 〜[classes /:na]原因: org.springframework.beans.factory.BeanCreationException:错误 创建在类路径中定义的名称为“ jedisConnectionFactory”的bean 资源[com / springboot / redisintegration / RedisConfiguration.class]: 调用init方法失败;嵌套异常为 redis.clients.jedis.exceptions.JedisConnectionException:所有标记 下来,无法确定mysentinel主服务器在哪里运行... org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0(AbstractBeanFactory.java:324) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:884) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:788) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE] ... 20个常见框架 省略的原因: redis.clients.jedis.exceptions.JedisConnectionException:所有标记 下来,无法确定mysentinel主服务器在哪里运行... redis.clients.jedis.JedisSentinelPool.initSentinels(JedisSentinelPool.java:249) 〜[jedis-3.3.0.jar:na]在 redis.clients.jedis.JedisSentinelPool。(JedisSentinelPool.java:154) 〜[jedis-3.3.0.jar:na]在 redis.clients.jedis.JedisSentinelPool。(JedisSentinelPool.java:122) 〜[jedis-3.3.0.jar:na]在 redis.clients.jedis.JedisSentinelPool。(JedisSentinelPool.java:116) 〜[jedis-3.3.0.jar:na]在 org.springframework.data.redis.connection.jedis.JedisConnectionFactory.createRedisSentinelPool(JedisConnectionFactory.java:374) 〜[spring-data-redis-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.data.redis.connection.jedis.JedisConnectionFactory.createPool(JedisConnectionFactory.java:358) 〜[spring-data-redis-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.data.redis.connection.jedis.JedisConnectionFactory.afterPropertiesSet(JedisConnectionFactory.java:342) 〜[spring-data-redis-2.3.3.RELEASE.jar:2.3.3.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) 〜[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE] ... 31个常见帧 省略
简而言之:
-
@Lazy
注释适用于RedisStandaloneConfiguration
,但不适用于RedisSentinelConfiguration
,不确定为什么吗? - 使用
@Lazy
注释是有风险的,因为您需要确保所有正在使用Redis
的服务也被延迟加载。 - 正在寻找为弹簧云提供的
spring.cloud.config.fail-fast=true
之类的解决方案。
更新:
我为此功能在Jira问题下面创建了>
https://jira.spring.io/browse/DATAREDIS-1208
解决方法
在后台,Spring Cloud Config使用spring-retry
和AOP(spring-boot-starter-aop
)来配置重试机制。
此过程在ConfigServiceBootstrapConfiguration中实现。
代码的相关部分是这样的:
/* @ConditionalOnProperty("spring.cloud.config.fail-fast") */
@ConditionalOnClass({ Retryable.class,Aspect.class,AopAutoConfiguration.class })
@Configuration(proxyBeanMethods = false)
@EnableRetry(proxyTargetClass = true)
@Import(AopAutoConfiguration.class)
@EnableConfigurationProperties(RetryProperties.class)
protected static class RetryConfiguration {
@Bean
@ConditionalOnMissingBean(name = "configServerRetryInterceptor")
public RetryOperationsInterceptor configServerRetryInterceptor(
RetryProperties properties) {
return RetryInterceptorBuilder.stateless()
.backOffOptions(properties.getInitialInterval(),properties.getMultiplier(),properties.getMaxInterval())
.maxAttempts(properties.getMaxAttempts()).build();
}
}
如您所见,基本思想是提供一个RetryConfiguration
来处理一定数量的重试,然后再考虑应用程序失败。
Spring Cloud Client的documentation提供了有关用于配置此机制的不同属性的更多信息。您还可以在RetryProperties
类的source code中看到默认值。
请尝试并包括两个必需的依赖项spring-retry
和spring-boot-starter-aop
,并将RetryConfiguration
作为主要配置的子项,为该配置的属性提供一些合理的默认值重试机制,看看会发生什么。
您可以将解决方案推到极限,并在很多情况下尝试重新连接,也许增加它们之间的频率,以等待服务器可用。
我认为@Lazy
注释将不再需要,可以安全地删除。
编辑
在查看错误堆栈跟踪时,您认为还可以尝试的方法是禁用String Boot Redis自动配置类。
您可以在注释中完成此操作
@SpringBootApplication(
exclude = { RedisAutoConfiguration.class,RedisRepositoriesAutoConfiguration.class }
)
或在您的属性文件中:
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration
您还可以使用此属性禁用Redis存储库配置:
spring.data.redis.repositories.enabled: false
一旦禁用Redis自动配置,您就可以随意实例化RedisTemplate
或在您认为适当时与Redis交互所需的内容。
例如,您可以根据需要初始化它,尝试通过在实际需要时初始化所有必需的工厂来建立与Redis的连接。您可以用try
和catch
包围初始化Redis连接所需的逻辑,并且仅在连接可用时初始化RedisTemplate
,如下所示。
一方面:
public RedisConnectionFactory jedisConnectionFactory() {
try {
// create set of sentinel nodes
System.out.println(SENTINEL_NODES);
Set<String> sentinelNodesSet = new HashSet<>(5);
StringTokenizer st = new StringTokenizer(SENTINEL_NODES,",");
while (st.hasMoreTokens())
sentinelNodesSet.add(st.nextToken());
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(SENTINEL_MASTER,sentinelNodesSet);
if (REDIS_SECURITY_ENABLED) {
sentinelConfig.setPassword(REDIS_PASSWORD);
}
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig);
return jedisConnectionFactory;
} catch (redis.clients.jedis.exceptions.JedisConnectionException re) {
logger.error("Unable to initialize Redis connection factory",re);
return null;
}
}
另一方面:
public RedisTemplate getRedisTemplate() {
// We can assume that both methods are defined in the same class,// although it is not necessary
final RedisConnectionFactory redisConnectionFactory = this.jedisConnectionFactory();
if (redisConnectionFactory == null) {
return null;
}
final RedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory);
return redisTemplate;
}
您可以按照自己认为合适的方式使用此RedisTemplate
,当然也可以根据需要缓存并重用它。
这些方法可以在为此任务创建的服务或帮助程序类中定义,当然不能在您的配置类中定义。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。