springCloud的Fegin+Hystrix熔斷器的熔斷降級
阿新 • • 發佈:2019-02-15
在分散式環境中,許多服務依賴項中會出現一些不可避免地失敗,比如說網路問題。Hystrix是一個庫,通過新增延遲容差和容錯邏輯來幫助您控制這些分散式服務之間的互動。Hystrix通過隔離服務之間的訪問點,停止其間的級聯故障以及提供回退選項,從而提高系統的整體彈性。本文講述的是Feign配合Hystrix在服務不可達時進行簡單容錯降級處理。
1、首先都是一成不變的pom.xml引入依賴
<!-- 新增feign支援 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> <!-- 新增對hystrix斷路器的依賴--> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>1.5.6</version> </dependency>
2、zbook-web服務啟動類檔案新增Feign註解@EnableFeignClients
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class ZbookWebApplication {
public static void main(String[] args){
SpringApplication.run(ZbookWebApplication.class,args);
}
}
3、zbook-web服務建立Feign呼叫介面,這個介面對接的是另外一個服務的controller,我這裡用的是restFulApi
@FeignClient(name = "zbook-service",fallback = IndexServiceHystrix.class)
public interface IndexService {
@RequestMapping(value = "/indexServiceApi/indexService/{id}",method = RequestMethod.POST)
String indexServiceApi(String params, @PathVariable("id") String id);
}
對應的另外一個服務是zbook-service,controller中的requestMapping就應該是下面這樣
@RestController
@RequestMapping("/indexServiceApi")
public class IndexServiceApiController {
@RequestMapping(value = "/indexService/1",method = RequestMethod.POST)
public String indexService(@RequestBody String params){
return "呼叫成功";
}
}
4、zbook-web服務建立服務容錯降級處理類,對應@FeignClient中的fallBack,當zbook-service服務不可用或者別的異常情況時,就會進入這個類進行容錯降級處理
@Service
public class IndexServiceHystrix implements IndexService {
@Override
public String indexServiceApi(String params, String id) {
return "IndexServiceHystrix 服務不可用";
}
}