繼之前項目繼續整合hystrix框架,hystrix框架爲Netflix的模塊,是一個容錯框架。當用戶訪問服務調用者的時候,如果服務提供者出現異常導致無法正常返回出現請求超時的情況,而服務調用者並不知情,還在繼續請求,這樣會導致服務的崩潰。
傳統的解決辦法:添加超時機制、人肉運維,而hystrix正是爲解決這一問題,它在服務調用者與服務提供者之間增加了容錯機制,當服務提供者無法提供服務的時候,服務調用者會根據設置的超時時間來阻斷請求,並調用回退邏輯。
1、添加hystrix依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2、在application.java類中加入@EnableCircuitBreaker斷路器註解。
3、在controller中加入類設置@DefaultProperties超時時間和最大線程值,我們爲/hello接口增加一個3秒的線程阻塞,把hystrix的超時時間設置爲2秒,讓該方法走回退邏輯。接口方法上的@HystrixCommand中的fallbackMethod參數就是回退邏輯的方法名。helloFallback()方法爲回退方法。
@RestController
@DefaultProperties(groupKey = "hello-groupKey",
commandProperties = {
// 超時時間(毫秒)
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
},
threadPoolProperties = {
// 最大線程數
@HystrixProperty(name = "coreSize", value = "2")
})
public class MyRestController {
@Autowired
private IService iService;
@GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@HystrixCommand(fallbackMethod = "helloFallback", commandKey = "hello-commandKey")
public String hello() throws InterruptedException {
Thread.sleep(3000);
String hello = iService.hello();
return "hello: " + hello;
}
public String helloFallback() {
return "helloFallback";
}
}