:-: 
* [ ] 服務降級
* [ ] 服務熔斷
* [ ] 依賴隔離
* [ ] 監控
## 服務降級
1. 引入依賴
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
```
2. 啟動類加上注解
``` @SpringBootApplication
@EnableCircuitBreaker
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.eclab.product.iclient")
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
```
隨著業務的不斷增加,注解也越來越多,此時有些注解可以使用另外的注解代替:
```
/*@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker*/
@SpringCloudApplication
@EnableFeignClients(basePackages = "com.eclab.product.iclient")
@EnableHystrixDashboard
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
```
服務降級實例:
```
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping("/getProductInfoList")
public String getProductInfoList(@RequestParam("i") Integer i){
if (i % 2 == 0){
return "Sucess";
}
RestTemplate restTemplate = new RestTemplate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return restTemplate.postForObject("http://localhost:8081/product/listForOrder",
Arrays.asList("157875152258154"),
String.class);
}
private String fallback(){
return "太擁擠了,請稍后再試~";
}
```
在服務降級中,除了調用的目標服務不可用導致的錯誤引起降級之外,自身的異常也可以進行降級
降級的方法除了自定外,還可以有個全局的通用方法,將注解加在類上:
```
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
//超時配置
/* @HystrixCommand(fallbackMethod = "fallback",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds" , value = "3000")
}
)*/
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled" , value = "true"), //設置熔斷
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold" , value = "10"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds" , value = "1000"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage" , value = "60")
})
@GetMapping("/getProductInfoList")
public String getProductInfoList(@RequestParam("i") Integer i){
if (i % 2 == 0){
return "Sucess";
}
RestTemplate restTemplate = new RestTemplate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return restTemplate.postForObject("http://localhost:8081/product/listForOrder",
Arrays.asList("157875152258154"),
String.class);
}
private String fallback(){
return "太擁擠了,請稍后再試~";
}
private String defaultFallback(){
return "默認提示:太擁擠了,請稍后再試~";
}
}
```
上面的代碼中的超時設置,可以用來配置是否降級