【问题标题】:Implementing Retry in Spring Cloud Application在 Spring Cloud 应用程序中实现重试
【发布时间】:2026-01-28 17:20:09
【问题描述】:

我目前正在尝试在 Zuul 代理应用程序中实现重试功能,该应用程序当前直接在路由配置下提供 url。直接在路由下指定url是否可以实现重试功能(如下例)?

zuul:
  prefix: /api
  sensitive-headers: Cookie,Set-Cookie
  routes:
    servicea:
      path: /servicea
      stripPrefix: true
      url: ${servicea.url}
    serviceb:
      path: /serviceab
      stripPrefix: true
      url: ${serviceb.url}

ribbon:
  ReadTimeout: 60000

应用程序指向由负载平衡器 (ALB) 前置的外部应用程序,因此在这种情况下不需要客户端负载平衡和服务发现。

应用程序正在使用 Zuul 的以下依赖项:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
  <version>2.1.2.RELEASE</version>
</dependency>

假设这是不可能的(文档似乎表明了这一点),我希望能获得一些帮助,了解我应该如何配置应用程序以启用重试。根据我阅读的内容,以下配置应该可以工作:

zuul:
  prefix: /api
  sensitive-headers: Cookie,Set-Cookie
  routes:
    servicea:
      path: /servicea
      stripPrefix: true
      retryable: true
      serviceId: servicea
    serviceb:
      path: /serviceab
      stripPrefix: true
      retryable: true
      serviceId: serviceb

 servicea:
   ribbon:
     ReadTimeout: 10000
     ConnectTimeout: 10000
     NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
     listOfServers: ${servicea.url}
     stripPrefix: true
     MaxAutoRetries: 1
     OkToRetryOnAllOperations: true

 serviceb:
   ribbon:
     ReadTimeout: 10000
     ConnectTimeout: 10000
     NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
     listOfServers: ${serviceb.url}
     stripPrefix: true
     MaxAutoRetries: 1
     OkToRetryOnAllOperations: true

 ribbon:
   IsSecure: true
   eureka:
     enabled: false
   ReadTimeout: 60000

当我尝试以这种方式实现它时,我遇到了一个问题,即应用程序不包含listOfServers 属性中指定的主机名。 HTTP 请求显然因此而失败(URL 只是协议、上下文路径和路径的其余部分)。

配置中的 URL 在启动期间被注入到 PropertySource 中。其中一个 URL 如下所示

https://servicea.domain/servicea

在此示例中,URL 是负载均衡器的 CNAME。第二种配置是按如下方式路由

Spring Cloud 应用程序的路径: /servicea/v1/someeapi

正在生成的网址:

https:/servicea/v1/someapi

如您所见,应用程序正在从导致请求失败的 URL 中删除主机和域。

我是否缺少此配置的某些内容? 我目前没有在应用程序的其他任何地方配置 Spring Cloud(除了在主类中提供 @EnableZuulProxy@EnableRetry 注释)。

【问题讨论】:

  • servicea.url 设置在哪里,它是什么样的?
  • @spencergibb 该值由在服务器启动期间将配置放入 PropertySource 的框架设置。第一个配置按预期工作。该值如下所示:https://servicea.domain/servicea(我尝试过排除上下文路径)
  • 如果直接设置而不是使用占位符,是否有效?
  • @spencergibb 我尝试用值替换占位符,但没有帮助。第一个配置与占位符或直接硬编码的值一起正常工作。奇怪的是日志表明功能区负载均衡器正在获取该值,它只是没有将它添加到它形成的 URL。
  • 如何重新创建问题的日志或项目。我现在只是猜测

标签: java spring spring-boot spring-cloud netflix-zuul


【解决方案1】:

重试失败的请求 Spring Cloud Netflix 提供了多种方式来发出 HTTP 请求。您可以使用负载平衡的 RestTemplate、Ribbon 或 Feign。无论您选择如何创建 HTTP 请求,请求总是有可能失败。当请求失败时,您可能希望自动重试请求。要在使用 Sping Cloud Netflix 时这样做,您需要在应用程序的类路径中包含 Spring Retry。当存在 Spring Retry 时,负载平衡的 RestTemplates、Feign 和 Zuul 会自动重试任何失败的请求(假设您的配置允许这样做)。

文档在这里:spring cloud retry

【讨论】: