SpringCloud-断路器Hystrix
一、降级使用
1、添加依赖
<!--hystrix--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>
2、启动类添加注解@EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {public static void main(String[] args) {SpringApplication.run(PaymentHystrixMain8001.class,args);}
}
3、超时或代码出错,降级代码fallbackMethod表示降级方法(服务提供方)
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})public String paymentInfo_TimeOut(Integer id){int timeNumber = 5;int age = 10/0;//try { TimeUnit.SECONDS.sleep(timeNumber); } catch (InterruptedException e) { e.printStackTrace(); }return "线程池:"+Thread.currentThread().getName()+" paymentInfo_TimeOut,id:"+id+"\t"+"O(∩_∩)O哈哈~"+" 耗时"+timeNumber+"秒";}public String paymentInfo_TimeOutHandler(Integer id){return "线程池:"+Thread.currentThread().getName()+" 系统繁忙,请稍后再试,id:"+id+"\t"+"呜呜~";}
4、消费方
主启动类添加注解@EnableHystrix
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class OrderHystrixMain80 {public static void main(String[] args) {SpringApplication.run(OrderHystrixMain80.class,args);}
}
降级代码
@GetMapping("/consumer/payment/hystrix/timeout/{id}")@HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")})public String paymentInfo_TimeOut(@PathVariable("id") Integer id){// int age = 10/0;String result = paymentHystrixService.paymentInfo_TimeOut(id);return result;}public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id){return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";}
二、全局降级
1、在controller类上添加@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")注解,并定义全局降级方法payment_Global_FallbackMethod。
2、在需要降级的方法上面添加注解@HystrixCommand
三、基于服务提供降级
添加配置
feign:hystrix:enabled: true
在openFeign接口上添加注解@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
创建降级类并实现openFeign接口
@Component
public class PaymentFallbackService implements PaymentHystrixService{@Overridepublic String paymentInfo_OK(Integer id) {return "----------------PaymentFallbackService fall back paymentInfo_OK";}@Overridepublic String paymentInfo_TimeOut(Integer id) {return "----------------PaymentFallbackService fall back paymentInfo_TimeOut";}
}
四、服务熔断
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸})public String paymentCircuitBreaker(@PathVariable("id") Integer id){if(id < 0){throw new RuntimeException("******id 不能负数");}String serialNumber = IdUtil.simpleUUID();return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber;}public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~ id: " +id;}
五、DashBoard搭建
添加配置,其中actuator依赖需要在每个被监控服务中添加
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
启动类上添加注解@EnableHystrixDashboard
访问http://localhost:9001/hystrix
在被监控服务启动类里面添加如下代码
/***此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑*ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",*只要在自己的项目里配置上下面的servlet就可以了*/@Beanpublic ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}
在上面打开的页面访问http://localhost:8001/hystrix.stream