在上一節存在的問題:每個業務方法對象一個兜底的方法,代碼膨脹,不可能每個方法都要一個處理異常的方法對應
使用global fallback全局配置
第一步:在類上使用@DefaultProperties注解,指定異常或超時等服務降級的方法 @RestController @Slf4j @DefaultProperties(defaultFallback = "timeoutGlobleHandler")//當使用hystrix服務降級時,沒有指定對應的方法,就來找到全局的服務降級對應方法 public class OrderController { 第二步:編寫處理方法 //全局配置降級方法 public CommonResult timeoutGlobleHandler(){ return new CommonResult(400,"全局消費端服務正忙,請稍后再試"); } 第三步:在需要降級的目標方法使用注解@HystrixCommand,當該方法出現錯誤時就會自動去找到降級處理的方法 @HystrixCommand @GetMapping("/consumer/findPaymentList") public CommonResult findPaymentList(){ log.info("查詢所有數據"); return orderService.findPaymentList(); }
但是之前每個對應方法指定的目標降級方法必須刪除掉或注釋掉,否則會發生沖突
/* @HystrixCommand(fallbackMethod ="timeoutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
})*/必須注釋掉
第四步:測試即可


但實際上不推薦使用在controller層上使用注解,我們直接定義一個類集成我們所需要調用的接口即可,方便管理
在工作中會遇上的問題無非三種:異常,超時,宕機
第一步:定義一個類OrderServiceFallback實現接口OrderService @Component public class OrderServiceFallback implements OrderService { @Override public CommonResult addPayment(Payment payment) { return new CommonResult(400,"添加方法服務正忙,請稍后再試"); } @Override public CommonResult findPaymentById(Long id) { return new CommonResult(400,"根據Id查找方法服務正忙,請稍后再試"); } @Override public CommonResult findPaymentList() { return new CommonResult(400,"查詢列表方法服務正忙,請稍后再試"); } } 第二步:在OrderService上使用fallback指定宕機或延時加載或異常指定的類fallback = OrderServiceFallback.class @Component @FeignClient(value = "cloud-hystrix-payment-service",fallback = OrderServiceFallback.class) //指定為服務名稱 public interface OrderService { 第三步:controller類,不能再方法和controller類上使用注解@DefaultProperties和@HystrixCommand @RestController @Slf4j public class OrderController { @Autowired private OrderService orderService; @PostMapping("/consumer/addPayment") public CommonResult addPayment(Payment payment){ return orderService.addPayment(payment); } @GetMapping("/consumer/findPaymentById/{id}") public CommonResult findPaymentById(@PathVariable("id")Long id){ log.info("消費端查找數據"); return orderService.findPaymentById(id); } @GetMapping("/consumer/findPaymentList") public CommonResult findPaymentList(){ log.info("查詢所有數據"); return orderService.findPaymentList(); } }
第四步:服務端不停,讓對應的線程睡眠,測試訪問

服務端停止宕機,同樣是一樣的結果

