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(全局处理返回方法)