本文介绍了带有 RestTemplate//Ribbon/Eureka 的 spring-cloud - 服务器不可用时重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地让我的 RestTemplate 客户端使用 Eureka 发现远程服务,并按照文档中的描述使用 Ribbon 将调用转发给它.基本上,只需在我的 Application 类中添加以下注释,然后让 Spring-Boot 的魔力完成剩下的工作:

I managed to successfully get my RestTemplate client discover remote service using Eureka and forward calls to it using Ribbon as described in the documentation.Basically, it was just a matter of adding the following annotations of my Application class and let the magic of Spring-Boot do the rest:

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableDiscoveryClient

(PS:您注意到我使用的是 spring-cloud:1.0.0-SNAPSHOT-BUILD 而不是 1.0.0.M3 - 但这似乎不会影响我的问题).

(PS: you noticed I'm using spring-cloud:1.0.0-SNAPSHOT-BUILD and not 1.0.0.M3 - but this doesn't seem to affect my problem).

当两个服务实例启动时,rest-template 客户端成功地对两者之间的请求进行负载均衡.但是,如果第一个实例在 Eureka 负载均衡器通知之前停止,则客户端不会回退到第二个实例,而是抛出异常.

When two service instances are started, the rest-template client successfully load balance requests between the two. However, the client won't fallback to the second instance if the first is stopped before the Eureka load balancer notices, instead an exception is thrown.

因此我的问题是:如果第一个选择的实例不可用,有没有办法配置 RestTemplate/Ribbon/Eureka 堆栈以自动重试对另一个实例的调用?Zuul 代理和伪装客户端开箱即用",所以我相信该库拥有必要的功能......

Hence my question: is there a way to configure the RestTemplate/Ribbon/Eureka stack to automatically retry the call to another instance if the one selected the first place is not available? Zuul proxy and feign clients do this "out of the box" so I believe the library holds the necessary features...

有什么想法/提示吗?

谢谢,/伯特兰

推荐答案

RestTemplate 支持本身不知道如何重试(而 Feign 客户端和 Spring Cloud 中的代理支持确实如此,正如您所注意到的).我认为这可能是一件好事,因为它让您可以选择自己添加它.例如,使用 Spring Retry,您可以以简单的声明式方式进行:

The RestTemplate support on its own does not know how to do any retrying (whereas the Feign client and the proxy support in Spring Cloud does, as you noticed). I think this is probably a good things because it gives you the option to add it yourself. For instance, using Spring Retry you can do it in a simple declarative style:

@Retryable
public Object doSomething() {
   // use your RestTemplate here
}

(并将 @EnableRetry 添加到您的 @Configuration).它与 @HystrixCommand(来自 Spring Cloud/Javanica)完美结合:

(and add @EnableRetry to your @Configuration). It makes a nice combination with @HystrixCommand (from Spring Cloud / Javanica):

@HystrixCommand
@Retryable
public Object doSomething() {
   // use your RestTemplate here
}

在这种形式中,即使重试成功,每次失败都计入断路器指标(也许我们可以改变它,或者保持原样).

In this form, every failure counts towards the circuit breaker metrics (maybe we could change that, or maybe it makes sense to leave it like that), even if the retry is successful.

这篇关于带有 RestTemplate//Ribbon/Eureka 的 spring-cloud - 服务器不可用时重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 11:48