1. Hystrix介紹
前面說到,微服務是将服務根據業務去分成一個個獨立的服務,服務之間通過RestTemplate+Ribbon或者Feign來調用,因為大多數微服務都會做成叢集,這樣就導緻如果其中某一個服務出現了問題,那麼調用這個服務的服務也同樣出現問題,慢慢的,整個服務都會崩掉(“雪崩效應”)。為了解決這個問題,斷路器誕生了
Netflix開源的Hystrix元件便是實作了斷路器模式,當某一個服務出現了問題,Hystrix會傳回一個提前預定的結果給調用方,這樣就可以避免連鎖的故障。
2.代碼實作
2.1 在Ribbon+RestTemplate中使用斷路器
- 準備兩個eureka-client服務,一個eureka-server服務,一個Ribbon服務(前面文章都有)
- 在Ribbon服務中整合Hystrix,pom.xml引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 在啟動類中加上注解@EnableHystrix來啟動Hystrix
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class HystrixRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- 在方法上加上@HystrixCommand注解來對該方法建立熔斷器的功能,并指定fallbackMethod熔斷方法(發生錯誤時調用的方法)
/**
* @author 呂梁山
* @date 2019/7/18
*/
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
private String service = "http://eureka-client";
@RequestMapping("test")
@HystrixCommand(fallbackMethod = "testErrorMethod")
public String test(String userName){
return restTemplate.getForObject(service + "/test?userName=" + userName, String.class);
}
public String testErrorMethod(String userName){
return "這是服務報錯傳回";
}
}
- 啟動服務,通路接口,會發現ribbon會去輪詢通路兩個client服務
http://localhost:5001/test?userName=測試
此次服務端口号:4001,接收到的參數:測試
此次服務端口号:4002,接收到的參數:測試
- 關閉其中一個服務,會發現ribbon去輪詢通路兩個client服務時傳回的分别是
此次服務端口号:4001,接收到的參數:測試
這是服務報錯傳回
由此可見,當某一個服務不可用時,Hystrix會傳回事先設定好的結果,而不是一直等待服務響應逾時
2.2 在Feign中使用斷路器
Feign中已經整合了Hystrix,是以不需要另外去導入,隻需要在配置檔案中去開啟即可
- 準備兩個eureka-client服務,一個eureka-server服務,一個Feign服務(前面文章都有)
- 在配置檔案中開啟Hystrix
feign:
hystrix:
enabled: true
- 建立一個類去實作之前寫的FeignService接口,并注入到Ioc容器中
/**
* @author 呂梁山
* @date 2019/7/18
*/
@Component
public class FeignServiceImpl implements FeignService {
@Override
public String test(String userName) {
return "這是服務報錯傳回";
}
}
- 在FeignService接口的注解中加上fallback指定到實作類
/**
* @author 呂梁山
* @date 2019/7/18
*/
@FeignClient(value = "eureka-client",fallback = FeignServiceImpl.class)
public interface FeignService {
@RequestMapping("test")
String test(@RequestParam(value = "userName") String userName);
}
- 啟動服務,通路接口,會發現ribbon會去輪詢通路兩個client服務
http://localhost:5001/test?userName=測試
此次服務端口号:4001,接收到的參數:測試
此次服務端口号:4002,接收到的參數:測試
- 關閉其中一個服務,傳回的分别是
此次服務端口号:4001,接收到的參數:測試
這是服務報錯傳回
歡迎留言:http://pikaqiu.vip/article/2369.html
示例代碼:https://github.com/Liangshan1994/SpringCloud