javascript
为Spring Cloud Ribbon配置请求重试(Camden.SR2+)
當我們使用Spring Cloud Ribbon實現客戶端負載均衡的時候,通常都會利用@LoadBalanced來讓RestTemplate具備客戶端負載功能,從而實現面向服務名的接口訪問(原理可見《Spring Cloud源碼分析(二)Ribbon》一文,如果對Spring Cloud中使用Ribbon進行服務消費還沒有概念的話,建議先閱讀《Spring Cloud構建微服務架構(二)服務消費者》一文。)。
下面的例子,實現了對服務名為hello-service的/hello接口的調用。由于RestTemplate被@LoadBalanced修飾,所以它具備客戶端負載均衡的能力,當請求真正發起的時候,url中的服務名會根據負載均衡策略從服務清單中挑選出一個實例來進行訪問。
public class Application { RestTemplate restTemplate() { return new RestTemplate(); } class ConsumerController { RestTemplate restTemplate; (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。
源碼定義如下:
("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配置),如果依然不行,返回失敗信息。
總結
以上是生活随笔為你收集整理的为Spring Cloud Ribbon配置请求重试(Camden.SR2+)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MSON,让JSON序列化更快
- 下一篇: 在Pivotal Web Service