在springboot中加入Hystrix

  • pom中加入maven依赖
<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>
  • springboot 配置类
import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class HystrixConfig {//用来拦截处理HystrixCommand注解@Beanpublic HystrixCommandAspect hystrixAspect() {return new HystrixCommandAspect();}//用来像监控中心Dashboard发送stream信息@Beanpublic ServletRegistrationBean hystrixMetricsStreamServlet() {ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());registration.addUrlMappings("/hystrix.stream");return registration;}} 
  • 实例controller

    @RestController
    @RequestMapping("/order")
    public class OrderController {Logger logger = LoggerFactory.getLogger(this.getClass());@Referenceprivate OrderService orderService;@RequestMapping(value = "/getOrderPageList", method = RequestMethod.POST)@HystrixCommand(fallbackMethod = "getOrderPageListFallback",threadPoolProperties = {  //10个核心线程池,超过20个的队列外的请求被拒绝; 当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务@HystrixProperty(name = "coreSize", value = "10"),@HystrixProperty(name = "maxQueueSize", value = "100"),@HystrixProperty(name = "queueSizeRejectionThreshold", value = "20")},commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"), //命令执行超时时间@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"), //若干10s一个窗口内失败三次, 则达到触发熔断的最少请求量@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000") //断路30s后尝试执行, 默认为5s})public Result getOrderPageList(@RequestBody PaginationQuery query) {//do something}public Result getOrderPageListFallback(@RequestBody PaginationQuery query){logger.error("===================== 执行降级策略");return Result.wrapDefaultErrorResult();}

    tip: 注意fallback的方法需要与被拦截的方法具有相同的签名,入参和返回值

  • 配置监控后台Hystrix-Dashboard

    1.github上下载源码https://github.com/kennedyoliveira/standalone-hystrix-dashboard

    2.参考其wiki文档,部署成功后,默认端口是7979;

    3.点击 http://127.0.0.1:7979/hystrix-dashboard 打开页面,出现小熊即为成功, 有个js是国外的,所以翻墙或者忍着等待;

说明:启动服务后,输入localhost:8001/hystrix.stream,之后点击”Add Stream”,最后点击”Monitor Stream”即可。

说明:(查看 HystrixCommand注解里边说明即可)

  • getHotelInfo - commandKey(其实就是servicename下的一个方法)

  • hotelService - ThreadPoolKey(不配置的情况下就是commandGroupKey,其实就是servicename)

Hystrix 参数详解及设置样例

 Hystrix 参数详解
hystrix.command.default和hystrix.threadpool.default中的default为默认CommandKeyCommand Properties
Execution相关的属性的配置:
hystrix.command.default.execution.isolation.strategy 隔离策略,默认是Thread, 可选Thread|Semaphorehystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令执行超时时间,默认1000mshystrix.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,默认trueCollapser Properties 相关参数
hystrix.collapser.default.maxRequestsInBatch 单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
hystrix.collapser.default.timerDelayInMilliseconds 触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
hystrix.collapser.default.requestCache.enabled 是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认trueThreadPool 相关参数
线程数默认值10适用于大部分情况(有时可以设置得更小),如果需要设置得更大,那有个基本得公式可以follow:
requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
每秒最大支撑的请求数 (99%平均响应时间 + 缓存值)
比如:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是:
1000 (0.060+0.012)基本得原则时保持线程池尽可能小,他主要是为了释放压力,防止资源被阻塞。
当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务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

后面附上项目中设置例:

[html] view plain copy
hystrix:   threadpool:   default:   coreSize: 500  #并发执行的最大线程数,默认10  command:   paas-file:   execution:   isolation:   thread:   timeoutInMilliseconds: 3600000   default:   execution:   isolation:   thread:   timeoutInMilliseconds: 8000  #命令执行超时时间,默认1000ms

在springboot中加入Hystrix相关推荐

  1. 在SpringBoot中使用Spring Session解决分布式会话共享问题

    在SpringBoot中使用Spring Session解决分布式会话共享问题 问题描述: 每次当重启服务器时,都会导致会员平台中已登录的用户掉线.这是因为每个用户的会话信息及状态都是由session ...

  2. SpringBoot 中 JPA 的使用

    前言 第一次使用 Spring JPA 的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的 CURD 的功能就出来了.下面我们就用一个例子来讲述以下 JPA 使用的基本操作 ...

  3. 难以想象SpringBoot中的条件注解底层居然是这样实现的

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源 | https://urlify.cn/bm2qqi Spr ...

  4. 面试:SpringBoot中的条件注解底层是如何实现的?

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源 | https://urlify.cn/bm2qqi Spr ...

  5. springboot yml怎么建常量_【Java】SpringBoot 中从application.yml中获取自定义常量

    由于这里我想通过java连接linux,connection连接需要host.port.username.password及其他路径等等.不想每次修改的时候都去改源文件,所以想写在applicatio ...

  6. Springboot中给图片添加文字水印

    Springboot中给图片添加文字水印 工作中遇到给图片添加文字水印的需求,记录下来方便之后查阅 需求内容: 给一张图片添加指定文字水印,使一张图片上有多个水印内容,并且设定一个水印开关,可指定是否 ...

  7. 你知道如何在springboot中使用redis吗

    特别说明:本文针对的是新版 spring boot 2.1.3,其 spring data 依赖为 spring-boot-starter-data-redis,且其默认连接池为 lettuce ​  ...

  8. WebSocket的故事(六)—— Springboot中,实现更灵活的WebSocket

    概述 WebSocket的故事系列计划分五大篇六章,旨在由浅入深的介绍WebSocket以及在Springboot中如何快速构建和使用WebSocket提供的能力.本系列计划包含如下几篇文章: 第一篇 ...

  9. SpringBoot 中 @RestController 和 @Controller 的区别

    1 - 在springboot中,@RestController 相当于 @Controller + @ResponseBody; 2 - 即在Controller类中,若想返回jsp或html页面, ...

最新文章

  1. hashmap value可以为空吗_美团面试题:Hashmap结构,1.7和1.8有哪些区别(最详细解析)...
  2. linux下java进程占用高问题分析过程
  3. spoj DPRSDCDR - Depressed Coder
  4. 力扣(LeetCode)258. 各位相加
  5. 31/100. Palindromic Substrings
  6. OpenCV4.0 Mask RCNN 实例分割示例 C++/Python实现
  7. mysql二级缓存redis_redis实现二级缓存
  8. 开发Flex for Android第一个ANE(ActionScript Native Extensions)本地扩展
  9. SQL中NOW() 函数
  10. 公关广告策略分析:如何结合广告的推力和公关的拉力
  11. 平行四边形不等式优化详解
  12. Requests 校花网图片爬取
  13. iOS TextField收取键盘的方法
  14. 一键启动oracle服务脚本,Oracle服务一键启动/关闭
  15. 批量写入mysql数据库的Python脚本
  16. 2022年4月28日 复盘计划
  17. echarts折线图,散点和折线点的点击事件
  18. 腾讯COS例程实践之云函数列举COS文件
  19. 基于intel低功耗平台边缘计算解决方案助力半导体设备升级
  20. 2020ICPC·小米 网络选拔赛热身赛 I-Integration

热门文章

  1. git版本回退及代码合并
  2. F. Asya And Kittens
  3. HSV2RGB一种灯光渐变实现算法
  4. qpython爬虫_python爬虫教程:批量抓取 QQ 群信息
  5. 用最简单易懂的方式告诉大家——区块链到底是什么?
  6. iptables防火墙之SNAT、DNAT策略及应用
  7. linux服务器中如何解压分卷文件,Linux解压rar文件(unrar安装和使用,分卷解压)...
  8. 交友项目【手机号登录注册功能】实现
  9. HDR的个人理解FAQ
  10. List 列表的用法