Hystrix Spring boot 结合

springboot项目直接引入hystrix,对于调用第三方接口的,用hystrix进行隔离,熔断控制

maven依赖

  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-hystrix</artifactId>
      <version>1.4.3.RELEASE</version>
    </dependency>

Controller

@Controller
public class HelloController {

  @GetMapping("hello/{name}")
  @ResponseBody
  public Object hello(@PathVariable("name") String name) {
    System.out.println("hello request come in. timestamp:" + System.currentTimeMillis());
    return service.doSth(name);
  }

  @Resource
  private HelloService service;
}

Service

@Service
public 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: 10
      maximumSize: 10
      maxQueueSize: -1

针对不同的组在配置文件里面加上不同的配置就好了,在@MyCommand注解里面指定group为abc就行;其他的配置也是这个规则,还有默认的配置是default;这样可以把一个组的配置独立出来,便于配置,而且开发者也会方便很多,代码简洁;下面附上所有的配置项供参考

#default可替换
hystrix:
  command:
    default:
      execution:
        isolation:
          #线程池隔离还是信号量隔离 默认是THREAD 信号量是SEMAPHORE
          strategy: THREAD
          semaphore:
            #使用信号量隔离时,支持的最大并发数 默认10
            maxConcurrentRequests: 10
          thread:
            #command的执行的超时时间 默认是1000
            timeoutInMilliseconds: 2000
            #HystrixCommand.run()执行超时时是否被打断 默认true
            interruptOnTimeout: true
            #HystrixCommand.run()被取消时是否被打断 默认false
            interruptOnCancel: false
        timeout:
          #command执行时间超时是否抛异常 默认是true
          enabled: true
        fallback:
          #当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback()
          enabled: true
          isolation:
            semaphore:
              #如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用 默认10
              maxConcurrentRequests: 10
      circuitBreaker:
        #用来跟踪熔断器的健康性,如果未达标则让request短路 默认true
        enabled: true
        #一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内
        #(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20
        requestVolumeThreshold: 5
        # 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内
        #都会拒绝request,也就是5000毫秒后才会关闭circuit,放部分请求过去。默认5000
        sleepWindowInMilliseconds: 5000
        #错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50
        errorThresholdPercentage: 50
        #强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
        forceOpen: false
        #强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略
        forceClosed: false
      metrics:
        rollingStats:
          #设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,
          #则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
          timeInMilliseconds: 10000
          #设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,
          #那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
          numBuckets: 10
        rollingPercentile:
          #执行时是否enable指标的计算和跟踪,默认true
          enabled: true
          #设置rolling percentile window的时间,默认60000
          timeInMilliseconds: 60000
          #设置rolling percentile window的numberBuckets。逻辑同上。默认6
          numBuckets: 6
          #如果bucket size=100,window=10s,若这10s里有500次执行,
          #只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
          bucketSize: 100
        healthSnapshot:
          #记录health 快照(用来统计成功和错误绿)的间隔,默认500ms
          intervalInMilliseconds: 500
      requestCache:
        #默认true,需要重载getCacheKey(),返回null时不缓存
        enabled: true
      requestLog:
        #记录日志到HystrixRequestLog,默认true
        enabled: true
  collapser:
    default:
      #单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
      maxRequestsInBatch: 2147483647
      #触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
      timerDelayInMilliseconds: 10
      requestCache:
        #是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true
        enabled: true
  threadpool:
    default:
      #并发执行的最大线程数,默认10
      coreSize: 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小于maximumSize
      allowMaximumSizeToDivergeFromCoreSize: false
      #如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。
      #如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.
      keepAliveTimeMinutes: 1
      metrics:
        rollingStats:
          #线程池统计指标的时间,默认10000
          timeInMilliseconds: 10000
          #将rolling window划分为n个buckets,默认10
          numBuckets: 10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值