繼以前項目繼續整合hystrix框架,hystrix框架爲Netflix的模塊,是一個容錯框架。當用戶訪問服務調用者的時候,若是服務提供者出現異常致使沒法正常返回出現請求超時的狀況,而服務調用者並不知情,還在繼續請求,這樣會致使服務的崩潰。html
須要JAVA Spring Cloud大型企業分佈式微服務雲構建的B2B2C電子商務平臺源碼請加企鵝求求 :二一四七七七五六三三java
傳統的解決辦法:添加超時機制、人肉運維,而hystrix正是爲解決這一問題,它在服務調用者與服務提供者之間增長了容錯機制,當服務提供者沒法提供服務的時候,服務調用者會根據設置的超時時間來阻斷請求,並調用回退邏輯。spring
一、添加hystrix依賴bash
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
複製代碼
二、在application.java類中加入@EnableCircuitBreaker斷路器註解。 三、在controller中加入類設置@DefaultProperties超時時間和最大線程值,咱們爲/hello接口增長一個3秒的線程阻塞,把hystrix的超時時間設置爲2秒,讓該方法走回退邏輯。接口方法上的@HystrixCommand中的fallbackMethod參數就是回退邏輯的方法名。helloFallback()方法爲回退方法。app
@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";
}
}
複製代碼