一、 什麼是斷路器?
斷路器在生活中,起到保護線路的作用,當電路發生負載、過熱等情況下,斷路器會開啓熔斷機制,切斷線路及時的保護用電,以免發生火災。
在分佈式環境下,經常會出現某個服務調用另外一個服務出現一直等待而不能及時的拿到響應的情況,比如網絡延遲或者其他故障導致的。特別是在高併發的場景下,一旦發生類似的情況,很容易引起服務的調用方的請求積壓,嚴重的情況下會直接導致服務調用方出現陣亡的情況。
Hystrix就是爲了解決這個問題而出現的。
二、 Hystrix應用
添加hystrix依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
1. ribbon結合hystrix
在啓動類上添加@EnableCircuitBreaker 註解開啓斷路器。
然後使用@HystrixCommand註解給調用的方法聲明一個回調方法,一旦被調用方發生故障,那麼會執行addServiceFallback()方法。給出"error"提示:
@Service
public class ComputeService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="addServiceFallback")
public String addService(){
return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?
a=10&b=20",String.class).getBody();
}
public String addServiceFallback(){
return "error";
}
}
2. feign 結合hystrix
1) 定義feign接口,指定服務名和回調的類對應的字節碼:
@FeignClient(value="compute-service",fallback=ComputeClientHystrix.class)
public interface ComputeClient {
@RequestMapping(method=RequestMethod.GET,value="/add")
Integer add(@RequestParam(value="a")Integer a,@RequestParam(value="b")Integer b);
}
2) 指定fallback屬性來定義回調方法,fallback指定的方法實現繼承feign定義的接口。
@Component
public class ComputeClientHystrix implements ComputeClient{
@Override
public Integer add(@RequestParam(value ="a")Integer a,@RequestParam(value="b")Integer b){
return "error";
}
}
feign接口調用失敗後,會回調自定義的 ComputeClientHystrix 類實現該feign服務調用的接口,並返回一個error提示。