springcloud實現熔斷降級機制
阿新 • • 發佈:2020-12-13
springcloud實現熔斷機制
熔斷降級機制作用在客戶端,在服務消費端實現
1、匯入依賴
<!--支援hystrix元件-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、定義降級方法
業務層使用feign實現,不用寫實現類,所以降級方法在控制器指定;如果使用RestTemplate實現,降級方法在業務層實現類指定
package com.yl.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.yl.bean.User; import com.yl.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private IUserService userService; @RequestMapping("/testHyStrix01") @HystrixCommand(fallbackMethod = "testHyStrix01FallBack")//指定降級方法 public String testHyStrix01(){ return userService.testHyStrix01(); } String testHyStrix01FallBack(){ return "請求服務不可用了,不要再來了"; } }
配置了熔斷降級啟動類上要新增@EnableHystrix註解