什麼是熔斷器?
熔斷器相當於電路當中的保險絲一樣,如果在一段時間內發生多次失敗,則會直接導致後續調用全部失敗。如果已修正,則應用程序會再次發起調用操作。
如何使用?
- 在創建新的springboot項目中勾選【Hystrix】或者pom裏增加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 在XXXApllication文件中增加@EnableCircuitBreaker 註解
- 改造之前的服務消費者,將RestTemplate封裝爲service
- 在service 中使用HystrixCommand註解需要降級的方法。
@Service
public class RestService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="indexfallback")
public String index(int i,int j)
{
return restTemplate.getForEntity("http://restservice1/xyf/hello",String.class).getBody();
}
public String indexfallback(int i,int j)
{
return "降級調用";
}
}
關鍵點:
@HystrixCommand(fallbackMethod=“indexfallback”)的意思是:當調用服務失敗的時候,調用indexfallback方法,fallbackMethod參數返回值要和原方法一樣。這種A方法調用失敗(比如請求出錯、服務器無法連接等),轉而調用B方法的做法叫“服務降級”,也可以在indexfallback中繼續標註@HystrixCommand,這樣如果indexfallback失敗那麼會繼續降級
異常處理
HystrixCommand方法中如果出現了任何異常,那麼會導致降級,前文已經提到,那麼如果說想要某些異常不導致服務降級,那麼可以使用HystrixCommand的ignoreExceptions指定多個異常。可以給接受降級的方法增加一個Throwable類型的參數,這樣當發生服務降級的時候,就可以得到異常信息。ignoreExceptions表示忽視異常。
例如:
@HystrixCommand(fallbackMethod="indexfallback",ignoreExceptions= {IllegalArgumentException.class)
@Service
public class RestService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="indexfallback",ignoreExceptions= {IllegalArgumentException.class})
public String index()
{
int i = 3;
if(i>0)
{
throw new NullPointerException("i3錯誤");
}
if(i==3)
{
throw new IllegalArgumentException("i錯誤");
}
return restTemplate.getForEntity("http://restservice1/xyf/hello",String.class).getBody();
}
public String indexfallback(Throwable t)
{
return "降級調用"+t;
}
}