9.hystrix服務降級
阿新 • • 發佈:2022-05-05
1.簡介
hystrix有三個主要功能:降級,熔斷,限流
2.降級使用場景
一般在客戶端使用
3.降級分為3類
a.單個方法降級
b.控制器中所有方法降級
c.所有控制器中方法降級
4.單個方法降級
以客戶端為例,在控制器中
/** * 測試單一服務降級方法 * @param id * @return */ @HystrixCommand(fallbackMethod = "paymentErrorStandby",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") }) @GetMapping("/timeout/{id}") public Object error(@PathVariable("id") Integer id){ try{ TimeUnit.SECONDS.sleep(5); }catch (Exception e){ e.printStackTrace(); } return paymentService.error(id); // 程式異常 // return 10/0; } public String paymentErrorStandby(Integer id) { return "8080埠返回:兜底方法"; }
5.單個控制器中方法降級
@RestController @Slf4j @RequestMapping("consumer") //@DefaultProperties(defaultFallback = "globalFallbackMethod") public class OrderController { /** * 測試(控制器中服務降級)預設全域性統一降級服務處理方法 * @HystrixCommand 如果不指定備用方法,會呼叫預設備用方法globalFallbackMethod * @return */ @GetMapping("/test") @HystrixCommand public Object test(){ return 10/0; } /** * 全域性統一降級服務處理方法 * @return */ public String globalFallbackMethod(){ return "兜底方法"; } }
6.所有控制器中方法降級
此處使用的是feign
寫一個全域性降級方法實現該介面,在上圖中加入fallback指定的這個實現類
7.yml
server: port: 8080 spring: application: name: cloud-consumer-hystrix-order8080 eureka: client: register-with-eureka: true #表示向註冊中心註冊自己 fetch-registry: true # 獲得登錄檔 service-url: # 請求註冊服務的地址 defaultZone: http://eureka7001:7001/eureka/ feign: hystrix: enabled: true
8.啟動類
@SpringBootApplication @EnableFeignClients // 感覺下面那個加不加都行 @EnableHystrix public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class, args); } }
9.pom
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
10.個人總結
c方法中:客戶端請求服務端,才會服務降級,自己請求介面內部報錯,降級是有問題的。