如何在Spring Boot中防止Redis服务器等外部连接失败时快速失败?

如何解决如何在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个常见帧 省略

简而言之

  1. @Lazy注释适用于RedisStandaloneConfiguration,但不适用于RedisSentinelConfiguration,不确定为什么吗?
  2. 使用@Lazy注释是有风险的,因为您需要确保所有正在使用Redis的服务也被延迟加载。
  3. 正在寻找为弹簧云提供的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-retryspring-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的连接。您可以用trycatch包围初始化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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-