hystrix全局降級(控制層面,解決方法膨脹)
一般情況下,我們會對客戶端控制層(controller)進行降級
調用接口異常返回:
服務器異常,請稍後再試
yml:(服務消費者)
server:
port: 80
eureka:
client:
register-with-eureka: false #表示是否將自己註冊進Eurekaserver默認爲true。
fetch-registry: true #是否M從Eurekaserver抓取已有的註冊信息,默認爲true。單節點無所謂,集羣必須設置爲true才能配合ribbon使用負載均衡
service-url:
defaultZone: http://localhost:7001/eureka
feign:
hystrix:
enabled: true
啓動類:(服務消費者)
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
@ComponentScan("com.zsp")
public class UserConsumerMain80 {
public static void main(String[] args) {
SpringApplication.run(UserConsumerMain80.class, args);
}
}
service接口(openfegin)
@FeignClient(value = "CLOUD-PROVEIDER-USER")
@Component
public interface UserService {
@GetMapping("/selectId/{id}")
public String selectId(@PathVariable("id") Long id);
}
controller(服務消費者)
@RestController
@DefaultProperties(defaultFallback = "globalFallbackMethod")
public class ZspController {
@Resource
private UserService userService;
@GetMapping("/zsp/{id}")
@HystrixCommand
public String selectId(@PathVariable("id") Long id) {
return userService.selectId(id);
}
public String globalFallbackMethod() {
return "服務器異常,請稍後再試";
}
}
總結:
-
啓動類@EnableCircuitBreaker
-
控制器層使用@DefaultProperties(defaultFallback =
“globalFallbackMethod”)註解來指定全局的fallback方法 -
添加globalFallbackMethod(全局處理返回方法)