當(dāng)我們使用Spring Cloud Ribbon實(shí)現(xiàn)客戶端負(fù)載均衡的時(shí)候,通常都會(huì)利用@LoadBalanced
來(lái)讓RestTemplate
具備客戶端負(fù)載功能啦租,從而實(shí)現(xiàn)面向服務(wù)名的接口訪問(wèn)哗伯。
下面的例子,實(shí)現(xiàn)了對(duì)服務(wù)名為hello-service
的/hello
接口的調(diào)用篷角。由于RestTemplate
被@LoadBalanced
修飾焊刹,所以它具備客戶端負(fù)載均衡的能力,當(dāng)請(qǐng)求真正發(fā)起的時(shí)候恳蹲,url中的服務(wù)名會(huì)根據(jù)負(fù)載均衡策略從服務(wù)清單中挑選出一個(gè)實(shí)例來(lái)進(jìn)行訪問(wèn)虐块。
@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);
}
}
大多數(shù)情況下,上面的實(shí)現(xiàn)沒(méi)有任何問(wèn)題嘉蕾,但是總有一些意外發(fā)生贺奠,比如:有一個(gè)實(shí)例發(fā)生了故障而該情況還沒(méi)有被服務(wù)治理機(jī)制及時(shí)的發(fā)現(xiàn)和摘除,這時(shí)候客戶端訪問(wèn)該節(jié)點(diǎn)的時(shí)候自然會(huì)失敗错忱。所以儡率,為了構(gòu)建更為健壯的應(yīng)用系統(tǒng),我們希望當(dāng)請(qǐng)求失敗的時(shí)候能夠有一定策略的重試機(jī)制以清,而不是直接返回失敗儿普。這個(gè)時(shí)候就需要開發(fā)人員人工的來(lái)為上面的RestTemplate
調(diào)用實(shí)現(xiàn)重試機(jī)制。
不過(guò)掷倔,從Spring Cloud Camden SR2版本開始眉孩,我們就不用那么麻煩了。從該版本開始今魔,Spring Cloud整合了Spring Retry來(lái)實(shí)現(xiàn)重試邏輯,而對(duì)于開發(fā)者只需要做一些配置即可障贸。
以上面對(duì)hello-service
服務(wù)的調(diào)用為例错森,我們可以在配置文件中增加如下內(nèi)容:
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
各參數(shù)的配置說(shuō)明:
-
spring.cloud.loadbalancer.retry.enabled
:該參數(shù)用來(lái)開啟重試機(jī)制,它默認(rèn)是關(guān)閉的篮洁。這里需要注意涩维,官方文檔中的配置參數(shù)少了enabled
。
源碼定義如下:
@ConfigurationProperties("spring.cloud.loadbalancer.retry")
public class LoadBalancerRetryProperties {
private boolean enabled = false;
...
}
-
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
:斷路器的超時(shí)時(shí)間需要大于ribbon的超時(shí)時(shí)間袁波,不然不會(huì)觸發(fā)重試瓦阐。 -
hello-service.ribbon.ConnectTimeout
:請(qǐng)求連接的超時(shí)時(shí)間 -
hello-service.ribbon.ReadTimeout
:請(qǐng)求處理的超時(shí)時(shí)間 -
hello-service.ribbon.OkToRetryOnAllOperations
:對(duì)所有操作請(qǐng)求都進(jìn)行重試 -
hello-service.ribbon.MaxAutoRetriesNextServer
:切換實(shí)例的重試次數(shù) -
hello-service.ribbon.MaxAutoRetries
:對(duì)當(dāng)前實(shí)例的重試次數(shù)
根據(jù)如上配置,當(dāng)訪問(wèn)到故障請(qǐng)求的時(shí)候篷牌,它會(huì)再嘗試訪問(wèn)一次當(dāng)前實(shí)例(次數(shù)由MaxAutoRetries
配置)睡蟋,如果不行,就換一個(gè)實(shí)例進(jìn)行訪問(wèn)枷颊,如果還是不行戳杀,再換一次實(shí)例訪問(wèn)(更換次數(shù)由MaxAutoRetriesNextServer
配置)该面,如果依然不行,返回失敗信息信卡。