springboot项目直接引入hystrix,对于调用第三方接口的,用hystrix进行隔离,熔断控制
maven依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-hystrix</artifactId><version>1.4.3.RELEASE</version></dependency>
Controller
@Controllerpublic class HelloController {@GetMapping("hello/{name}")@ResponseBodypublic Object hello(@PathVariable("name") String name) {System.out.println("hello request come in. timestamp:" + System.currentTimeMillis());return service.doSth(name);}@Resourceprivate HelloService service;}
Service
@Servicepublic class HelloService {@HystrixCommand(groupKey = "helloGroup", commandKey = "hello")public String doSth(String username) {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}return username + " do something.";}public static void main(String[] args) {System.out.println(Integer.MAX_VALUE);}}
最简单的方式就是通过HystrixCommand注解来启用Hystrix,但是这里比较麻烦的是,多个方法都要使用HystrixCommand,那注解每个都要写,而且同一个组内的command应该公用同一个配置,那么请看下面的application.yml的配置,解决问题
调用第三方系统helloGroup走HyStrixCommand
hystrix.threadpool.helloGroup.coreSize=10hystrix.threadpool.helloGroup.maximumSize=10hystrix.threadpool.helloGroup.maxQueueSize=-1
针对不同的组在配置文件里面加上不同的配置就好了,在@MyCommand注解里面指定group为abc就行;其他的配置也是这个规则,还有默认的配置是default;这样可以把一个组的配置独立出来,便于配置,而且开发者也会方便很多,代码简洁;下面附上所有的配置项供参考
#default可替换hystrix:command:default:execution:isolation:#线程池隔离还是信号量隔离 默认是THREAD 信号量是SEMAPHOREstrategy: THREADsemaphore:#使用信号量隔离时,支持的最大并发数 默认10maxConcurrentRequests: 10thread:#command的执行的超时时间 默认是1000timeoutInMilliseconds: 2000#HystrixCommand.run()执行超时时是否被打断 默认trueinterruptOnTimeout: true#HystrixCommand.run()被取消时是否被打断 默认falseinterruptOnCancel: falsetimeout:#command执行时间超时是否抛异常 默认是trueenabled: truefallback:#当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback()enabled: trueisolation:semaphore:#如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用 默认10maxConcurrentRequests: 10circuitBreaker:#用来跟踪熔断器的健康性,如果未达标则让request短路 默认trueenabled: true#一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内#(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20requestVolumeThreshold: 5# 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内#都会拒绝request,也就是5000毫秒后才会关闭circuit,放部分请求过去。默认5000sleepWindowInMilliseconds: 5000#错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50errorThresholdPercentage: 50#强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认falseforceOpen: false#强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略forceClosed: falsemetrics:rollingStats:#设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,#则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000timeInMilliseconds: 10000#设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,#那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10numBuckets: 10rollingPercentile:#执行时是否enable指标的计算和跟踪,默认trueenabled: true#设置rolling percentile window的时间,默认60000timeInMilliseconds: 60000#设置rolling percentile window的numberBuckets。逻辑同上。默认6numBuckets: 6#如果bucket size=100,window=10s,若这10s里有500次执行,#只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100bucketSize: 100healthSnapshot:#记录health 快照(用来统计成功和错误绿)的间隔,默认500msintervalInMilliseconds: 500requestCache:#默认true,需要重载getCacheKey(),返回null时不缓存enabled: truerequestLog:#记录日志到HystrixRequestLog,默认trueenabled: truecollapser:default:#单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUEmaxRequestsInBatch: 2147483647#触发批处理的延迟,也可以为创建批处理的时间+该值,默认10timerDelayInMilliseconds: 10requestCache:#是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认trueenabled: truethreadpool:default:#并发执行的最大线程数,默认10coreSize: 10#Since 1.5.9 能正常运行command的最大支付并发数maximumSize: 10#BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。#该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。#默认-1。maxQueueSize: -1#即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。#因为maxQueueSize不能被动态修改,这个参数将允许我们动态设置该值。if maxQueueSize == -1,该字段将不起作用queueSizeRejectionThreshold: 5#Since 1.5.9 该属性使maximumSize生效,值须大于等于coreSize,当设置coreSize小于maximumSizeallowMaximumSizeToDivergeFromCoreSize: false#如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。#如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.keepAliveTimeMinutes: 1metrics:rollingStats:#线程池统计指标的时间,默认10000timeInMilliseconds: 10000#将rolling window划分为n个buckets,默认10numBuckets: 10
