當我們使用Spring Cloud Ribbon實現客戶端負載均衡的時候,通常都會利用@LoadBalanced
來讓RestTemplate
具備客戶端負載功能,從而實現面向服務名的接口訪問。
下面的例子,實現了對服務名為hello-service
的/hello
接口的調用。由于RestTemplate
被@LoadBalanced
修飾,所以它具備客戶端負載均衡的能力,當請求真正發起的時候,url中的服務名會根據負載均衡策略從服務清單中挑選出一個實例來進行訪問。
@SpringCloudApplication
public class Application {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@RestController
class ConsumerController {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
public String helloConsumer() {
return restTemplate.getForObject("http://hello-service/hello", String.class);
}
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
大多數情況下,上面的實現沒有任何問題,但是總有一些意外發生,比如:有一個實例發生了故障而該情況還沒有被服務治理機制及時的發現和摘除,這時候客戶端訪問該節點的時候自然會失敗。所以,為了構建更為健壯的應用系統,我們希望當請求失敗的時候能夠有一定策略的重試機制,而不是直接返回失敗。這個時候就需要開發人員人工的來為上面的RestTemplate
調用實現重試機制。
不過,從Spring Cloud Camden SR2版本開始,我們就不用那么麻煩了。從該版本開始,Spring Cloud整合了Spring Retry來實現重試邏輯,而對于開發者只需要做一些配置即可。
以上面對hello-service
服務的調用為例,我們可以在配置文件中增加如下內容:
spring.cloud.loadbalancer.retry.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000
hello-service.ribbon.ConnectTimeout=250
hello-service.ribbon.ReadTimeout=1000
hello-service.ribbon.OkToRetryOnAllOperations=true
hello-service.ribbon.MaxAutoRetriesNextServer=2
hello-service.ribbon.MaxAutoRetries=1
各參數的配置說明:
-
spring.cloud.loadbalancer.retry.enabled
:該參數用來開啟重試機制,它默認是關閉的。這里需要注意,官方文檔中的配置參數少了enabled
。
源碼定義如下:
@ConfigurationProperties("spring.cloud.loadbalancer.retry")
public class LoadBalancerRetryProperties {
private boolean enabled = false;
...
}
-
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
:斷路器的超時時間需要大于ribbon的超時時間,不然不會觸發重試。 -
hello-service.ribbon.ConnectTimeout
:請求連接的超時時間 -
hello-service.ribbon.ReadTimeout
:請求處理的超時時間 -
hello-service.ribbon.OkToRetryOnAllOperations
:對所有操作請求都進行重試 -
hello-service.ribbon.MaxAutoRetriesNextServer
:切換實例的重試次數 -
hello-service.ribbon.MaxAutoRetries
:對當前實例的重試次數
根據如上配置,當訪問到故障請求的時候,它會再嘗試訪問一次當前實例(次數由MaxAutoRetries
配置),如果不行,就換一個實例進行訪問,如果還是不行,再換一次實例訪問(更換次數由MaxAutoRetriesNextServer
配置),如果依然不行,返回失敗信息。