springCloud微服务组件:熔断器(Hystrix)
降级
消费方调用提供方接口,提供方如果出异常了,需要向消费方返回一个降级方法
1.提供方降级
-
导入Hystrix对应的坐标,才能向消费方提供降级的方法
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
-
编写服务接口对应的降级方案,要用@HystrixCommand注解声明这是一个降级方法
package com.gwx.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class ProviderController { @RequestMapping("/hello") // 指定这个接口出现异常调用的降级方法 @HystrixCommand(fallbackMethod = "hello_fallback",commandProperties = { // 表示这个接口超时多少秒出现异常才会去调用降级的方法 @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") }) public String hello(){ return "hello nacos"; } // 定义降级的方法 public String hello_fallback(){ return "降级了"; } }
-
在启动类开启Hystrix的服务降级的功能
@SpringBootApplication
@EnableCircuitBreaker
public class ProviderApp {
public