hystrix 能使你的系统在出现依赖服务失效的时候,通过隔离系统所依赖的服务,防止服务级联失败,同时提供失败回退机制,更优雅地应对失效,并使你的系统能更快地从异常中恢复。
货船为了进行防止漏水和火灾的扩散,会将货仓分隔为多个,当发生灾害时,将所在货仓进行隔离就可以降低整艘船的风险。
熔断器就像家里的保险丝,当电流过载了就会跳闸,不过hystrix的熔断机制相对复杂一些。
熔断器开关由关闭到打开的状态转换是通过当前服务健康状况和设定阈值比较决定的.
使用一个线程池来存储当前的请求,线程池对请求作处理,设置任务返回处理超时时间,堆积的请求堆积入线程池队列。这种方式需要为每个依赖的服务申请线程池,有一定的资源消耗,好处是可以应对突发流量(流量洪峰来临时,处理不完可将数据存储到线程池队里慢慢处理)。
使用一个原子计数器(或信号量)来记录当前有多少个线程在运行,请求来先判断计数器的数值,若超过设置的最大线程个数则丢弃改类型的新请求,若不超过则执行计数操作请求来计数器+1,请求返回计数器-1。这种方式是严格的控制线程且立即返回模式,无法应对突发流量(流量洪峰来临时,处理的线程超过数量,其他的请求会直接返回,不继续去请求依赖的服务)。
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>com.netflix.hystrix</groupid> <artifactid>hystrix-core</artifactid> <version>1.5.12</version> </dependency> <dependency> <groupid>com.netflix.hystrix</groupid> <artifactid>hystrix-metrics-event-stream</artifactid> <version>1.5.12</version> </dependency> <dependency> <groupid>com.netflix.hystrix</groupid> <artifactid>hystrix-javanica</artifactid> <version>1.5.12</version> </dependency>
@configuration public class hystrixconfig { /** * 声明一个hystrixcommandaspect代理类,现拦截hystrixcommand的功能 */ @bean public hystrixcommandaspect hystrixcommandaspect() { return new hystrixcommandaspect(); } }
@service public class helloservice { @hystrixcommand(fallbackmethod = "helloerror", commandproperties = { @hystrixproperty(name = "execution.isolation.strategy", value = "thread"), @hystrixproperty(name = "execution.isolation.thread.timeoutinmilliseconds", value = "1000"), @hystrixproperty(name = "circuitbreaker.enabled", value = "true"), @hystrixproperty(name = "circuitbreaker.requestvolumethreshold", value = "2")}, threadpoolproperties = { @hystrixproperty(name = "coresize", value = "5"), @hystrixproperty(name = "maximumsize", value = "5"), @hystrixproperty(name = "maxqueuesize", value = "10") }) public string sayhello(string name) { try { thread.sleep( 15000 ); return "hello " + name + " !"; } catch (interruptedexception e) { e.printstacktrace(); } return null; } public string helloerror(string name) { return "服务器繁忙,请稍后访问~"; } }
@springbootapplication @restcontroller public class hystrixsimpleapplication { @autowired private helloservice helloservice; public static void main(string[] args) { springapplication.run( hystrixsimpleapplication.class, args ); } @getmapping("/hi") public string hi(string name) { return helloservice.sayhello( name ); } }
访问 http://localhost:80809/hi?name=zhangsan
curl -x get -d 'name=zhangsan' http://localhost:8080/hi
返回
服务器繁忙,请稍后访问~
https://github.com/gf-huanchupk/springcloudlearning/tree/master/chapter16
https://github.com/netflix/hystrix/wiki
https://blog.51cto.com/snowtiger/2057092
欢迎扫码或微信搜索公众号《程序员果果》关注我,关注有惊喜~
如对本文有疑问, 点击进行留言回复!!
SpringBoot项目部署到服务器之 Liunx环境安装jdk详细步骤
网友评论