當我們使用Spring Cloud Ribbon實現客戶端負載均衡的時候,通常都會利用@LoadBalanced來讓RestTemplate具備客戶端負載功能,從而實現面向服務名的接口訪問。
需要JAVA Spring Cloud大型企業分佈式微服務雲構建的B2B2C電子商務平臺源碼:壹零叄八柒柒肆六二六
下面的例子,實現了對服務名爲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配置),如果依然不行,返回失敗信息。