如何在 spring 启动时设置重试配置提取?

How set up retry config fetching in spring boot?

我有配置服务器,应用程序从该服务器获取配置。 我想设置抓取的重试机制。如果配置服务器不可用,应用程序应发送请求 10 分钟。

在 spring 文档中我找到了下一个配置

spring.cloud.config.uri=http://localhost:9090
spring.cloud.config.fail-fast=true
spring.cloud.config.retry.max-interval=10000
spring.cloud.config.retry.max-attempts=2000

但他们什么也没改变。我的应用程序不执行重试请求,它只是失败

Caused by: java.net.ConnectException: Connection refused: connect 

(当时配置服务器已关闭)

我做错了什么?有办法解决我的问题吗?

您将 spring.cloud.config.fail-fast 设置为 true。根据文档,这将暂停您的应用程序并不会重试连接。

来源:https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_client.html#config-client-fail-fast

我通过将下一个@Bean 添加到上下文解决了我的问题

@Bean
    public RetryOperationsInterceptor configServerRetryInterceptor(RetryProperties properties) {
        return RetryInterceptorBuilder
                .stateless()
                .backOffOptions(properties.getInitialInterval(),
                        properties.getMultiplier(),
                        properties.getMaxInterval())
                .maxAttempts(properties.getMaxAttempts()).build();
    }

根据问题中的信息,我认为您的 class 路径中缺少以下依赖项:

        <!-- for auto retry -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
        <version>1.2.4.RELEASE</version>
    </dependency>
    <!-- for auto retry -->

答案是前两个答案的组合:

  • 您需要设置spring.cloud.config.fail-fast=true
  • 您还需要将 spring-retryspring-boot-starter-aop 添加到您的类路径中。

查看文档 here