🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
:-: ![](https://box.kancloud.cn/a54df87c41d8c37d28e950ea4c8cc501_667x237.png) * [ ] 服务降级 * [ ] 服务熔断 * [ ] 依赖隔离 * [ ] 监控 ## 服务降级 1. 引入依赖 ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> ``` 2. 启动类加上注解 ``` @SpringBootApplication @EnableCircuitBreaker @EnableDiscoveryClient @EnableFeignClients(basePackages = "com.eclab.product.iclient") public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } } ``` 随着业务的不断增加,注解也越来越多,此时有些注解可以使用另外的注解代替: ``` /*@SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker*/ @SpringCloudApplication @EnableFeignClients(basePackages = "com.eclab.product.iclient") @EnableHystrixDashboard public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } } ``` 服务降级实例: ``` @HystrixCommand(fallbackMethod = "fallback") @GetMapping("/getProductInfoList") public String getProductInfoList(@RequestParam("i") Integer i){ if (i % 2 == 0){ return "Sucess"; } RestTemplate restTemplate = new RestTemplate(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return restTemplate.postForObject("http://localhost:8081/product/listForOrder", Arrays.asList("157875152258154"), String.class); } private String fallback(){ return "太拥挤了,请稍后再试~"; } ``` 在服务降级中,除了调用的目标服务不可用导致的错误引起降级之外,自身的异常也可以进行降级 降级的方法除了自定外,还可以有个全局的通用方法,将注解加在类上: ``` @RestController @DefaultProperties(defaultFallback = "defaultFallback") public class HystrixController { //超时配置 /* @HystrixCommand(fallbackMethod = "fallback", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds" , value = "3000") } )*/ @HystrixCommand(commandProperties = { @HystrixProperty(name = "circuitBreaker.enabled" , value = "true"), //设置熔断 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold" , value = "10"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds" , value = "1000"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage" , value = "60") }) @GetMapping("/getProductInfoList") public String getProductInfoList(@RequestParam("i") Integer i){ if (i % 2 == 0){ return "Sucess"; } RestTemplate restTemplate = new RestTemplate(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return restTemplate.postForObject("http://localhost:8081/product/listForOrder", Arrays.asList("157875152258154"), String.class); } private String fallback(){ return "太拥挤了,请稍后再试~"; } private String defaultFallback(){ return "默认提示:太拥挤了,请稍后再试~"; } } ``` 上面的代码中的超时设置,可以用来配置是否降级