# Hystrix簡介
Hystrix是netflix的一個開源項目,它能夠在依賴服務失效的情況下,通過隔離系統依賴服務的方式,防止服務級聯失敗;同時Hystrix提供失敗回滾機制,使系統能夠更快的從異常中恢復。spring-cloud-netflix-hystrix 對Hystrix進行了封裝和適配,為微服務間調用提供強有力的容錯機制
*****
## 1、RestTemplate與Hystrix
首先添加eureka-client和hystrix的相關依賴;
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
```
通過@EnableCircuitBreaker注解開啟Hystrix,同時注入可以負載均衡的RestTemplate,代碼如下:
```
@SpringBootApplication
@EnableCircuitBreaker // 開啟Hystrix
public class HystrixApplication{
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
```
在調用的方法上添加注解@HystrixCommand,方式如下:
```
@Service
public class Service{
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "getFail") // 指定調用失敗的方法
public String getName(){
retrun restTemplate.getForEntity(url);
}
public String getFail(){
retrun "error";
}
}
```
## 2、OpenFeign與Hystrix
OpenFeign是自帶Hystrix,默認沒有打開,需要在application.yml中添加配置開啟:
```
feign:
hystrix:
enabled: true
# hystrix配置
hystrix:
metrics:
enabled: true
# 默認的超時時間設置 單位為毫秒
hystrix:
metrics:
polling-interval-ms: 2000
```
啟動類添加注解@EnableFeignClients @EnableCircuitBreaker
在調用service服務時,指定失敗回滾類:
```
@FeignClient(value = "feign-service" ,fallback = ClientFallback.class)
public interface Client {
}
// ClientFallback 類實現 Client
public class ClientFallback implements Client {
}
```