spring 熔断 Hystrix

目录

快速使用

添加依赖

配置切面

编写接口

@hystrixCommand参数

@hystrixProperty参数

源码


原理讲解
Hystrix 使用手册 | 官方文档翻译 - 闪客sun - 博客园

Hystrix原理与实战_校长我错了的博客-CSDN博客_hystrix

快速使用

添加依赖

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-core</artifactId>
    <version>1.5.18</version>
</dependency>
<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-javanica</artifactId>
    <version>1.5.18</version>
</dependency>

配置切面

在spring-***.xml中添加

<!--开启切面 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect" />

编写接口

@Controller
@RequestMapping
public class CommonController {
    /**
     * 主页
     * 
     * @return
     */
    @RequestMapping("/")
    public String home() {
        return "home.html";
    }

    /**
     * 配置2秒超时,超时后调用testFallback方法返回到error界面<br>
     * 当并发量比较大时,并非所有阻断或失败的请求都会走fallback方法,当处理线程忙不过来时,会直接抛出HystrixRuntimeException异常
     * 
     * @param mav
     * @param time 睡眠时间
     * @return
     */
     @HystrixCommand(groupKey = "AcceptMessage", commandKey = "handleMessage", fallbackMethod = "hystrixResponse", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "120000"), // 命令执行超时时间,默认1000ms
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000"), // 熔断后恢复时间ms
            @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "15"), // 如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
            @HystrixProperty(name = "metrics.rollingPercentile.enabled", value = "false"), // 执行时是否metrics指标的计算和跟踪,默认true
    },threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "30") // 断路器默认是Thread 配置核心线程数 超过该值会进行服务降级
    })
    @RequestMapping("/test")
    public ModelAndView test(ModelAndView mav, @RequestParam(defaultValue = "1") int time) {
        try {
            Thread.sleep(1000 * time);
        } catch (Exception e) {
        }
        mav.setViewName("success.html");
        return mav;
    }

    /**
     * test访问熔断后回调页面
     * 
     * @param mav
     * @param time
     * @return
     */
    protected ModelAndView testFallback(ModelAndView mav, @RequestParam(defaultValue = "1") int time) {
        mav.setViewName("fallback.html");
        return mav;
    }
}

@hystrixCommand参数

public @interface HystrixCommand {

            // HystrixCommand 命令所属的组的名称:默认注解方法类的名称
            String groupKey() default "";

            // HystrixCommand 命令的key值,默认值为注解方法的名称
            String commandKey() default "";

            // 线程池名称,默认定义为groupKey
            String threadPoolKey() default "";
            // 定义回退方法的名称, 此方法必须和hystrix的执行方法在相同类中
            String fallbackMethod() default "";
            // 配置hystrix命令的参数
            HystrixProperty[] commandProperties() default {};
            // 配置hystrix依赖的线程池的参数
            HystrixProperty[] threadPoolProperties() default {};

            // 如果hystrix方法抛出的异常包括RUNTIME_EXCEPTION,则会被封装HystrixRuntimeException异常。我们也可以通过此方法定义哪些需要忽略的异常
            Class<? extends Throwable>[] ignoreExceptions() default {};

            // 定义执行hystrix observable的命令的模式,类型详细见ObservableExecutionMode
            ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;

            // 如果hystrix方法抛出的异常包括RUNTIME_EXCEPTION,则会被封装HystrixRuntimeException异常。此方法定义需要抛出的异常
            HystrixException[] raiseHystrixExceptions() default {};

            // 定义回调方法:但是defaultFallback不能传入参数,返回参数和hystrix的命令兼容
            String defaultFallback() default "";
        }

@hystrixProperty参数

该注解只用于@hystrixCommand 注解中的threadPoolProperties、commandProperties属性上,见上文的参数和编写接口中的使用案例

使用的时候去掉hystrix.command.default即可(见编写接口中的示例,这个命名是源码中写死的)

hystrix.command.default.metrics 开头的的参数为一种较为复杂熔断实现的计算方式,本人在实际项目中没有使用设置为false了,机制详解

hystrix熔断器之metrics - zwh1988 - 博客园

hystrix.command.default和hystrix.threadpool.default中的default为默认CommandKey

Command Properties 
-------------------------------- commandProperties中的参数
Execution相关的属性的配置:
hystrix.command.default.execution.isolation.strategy 隔离策略,默认是Thread, 可选Thread|Semaphore

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令执行超时时间,默认1000ms          

hystrix.command.default.execution.timeout.enabled 执行是否启用超时,默认启用true

hystrix.command.default.execution.isolation.thread.interruptOnTimeout 发生超时是是否中断,默认true
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 最大并发请求数,默认10,该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致,但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。
semaphore应该占整个容器(tomcat)的线程池的一小部分。
Fallback相关的属性
这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略

hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
hystrix.command.default.fallback.enabled 当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback() 。默认true
Circuit Breaker相关的属性
hystrix.command.default.circuitBreaker.enabled 用来跟踪circuit的健康性,如果未达标则让request短路。默认true
hystrix.command.default.circuitBreaker.requestVolumeThreshold 一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20

hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内都会拒绝request,也就是5000毫秒后才会关闭circuit。默认5000
hystrix.command.default.circuitBreaker.errorThresholdPercentage错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50
hystrix.command.default.circuitBreaker.forceOpen 强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
hystrix.command.default.circuitBreaker.forceClosed 强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略circuitBreaker.errorThresholdPercentage
Metrics相关参数
hystrix.command.default.metrics.rollingStats.timeInMilliseconds 设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
hystrix.command.default.metrics.rollingStats.numBuckets 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
hystrix.command.default.metrics.rollingPercentile.enabled 执行时是否enable指标的计算和跟踪,默认true
hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 设置rolling percentile window的时间,默认60000
hystrix.command.default.metrics.rollingPercentile.numBuckets 设置rolling percentile window的numberBuckets。逻辑同上。默认6
hystrix.command.default.metrics.rollingPercentile.bucketSize 如果bucket size=100,window=10s,若这10s里有500次执行,只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 记录health 快照(用来统计成功和错误绿)的间隔,默认500ms
Request Context 相关参数
hystrix.command.default.requestCache.enabled 默认true,需要重载getCacheKey(),返回null时不缓存
hystrix.command.default.requestLog.enabled 记录日志到HystrixRequestLog,默认true



-------------------------------- commandProperties中的参数



Collapser Properties 相关参数
hystrix.collapser.default.maxRequestsInBatch 单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
hystrix.collapser.default.timerDelayInMilliseconds 触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
hystrix.collapser.default.requestCache.enabled 是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true

ThreadPool 相关参数
线程数默认值10适用于大部分情况(有时可以设置得更小),如果需要设置得更大,那有个基本得公式可以follow:
requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
每秒最大支撑的请求数 (99%平均响应时间 + 缓存值)
比如:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是:
(0.060+0.012)

基本得原则时保持线程池尽可能小,他主要是为了释放压力,防止资源被阻塞。
当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务


-----------------------------------------------------------threadpool中的参数
hystrix.threadpool.default.coreSize 并发执行的最大线程数,默认10
hystrix.threadpool.default.maxQueueSize BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。默认-1。
hystrix.threadpool.default.queueSizeRejectionThreshold 即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。因为maxQueueSize不能被动态修改,这个参数将允许我们动态设置该值。if maxQueueSize == -1,该字段将不起作用
hystrix.threadpool.default.keepAliveTimeMinutes 如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.
hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds 线程池统计指标的时间,默认10000
hystrix.threadpool.default.metrics.rollingStats.numBuckets 将rolling window划分为n个buckets,默认10

Hystrix 用法,@HystrixProperty参数说明_佛说"獨" 的博客-CSDN博客

hystrix(4) properties配置 - zwh1988 - 博客园

源码

源码中实现功能的入口,可以自己debug多调试几遍看看,还是很有意思的工具

小记:hystrix实现是使用的aop切面的形式,也就是说如果你@hystrixCommand里面的参数名称写错了,其实在启动的时候是不会报错的,但是在调用该接口的时候就会报错

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值