SpringCloud-Hystrix-01入门介绍

Hystrix是由Netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败,从而提升系统的可用性与容错性。Hystrix主要通过以下几点实现延迟和容错。

  • 跳闸机制:当某服务的错误率超过一定阈值时,Hystrix可以自动或者手动跳闸,停止请求该服务一段时间。
  • 资源隔离:Hystrix为每个依赖都维护了一个小型的线程池(或者信号量)。如果该线程池已满,发往该依赖的请求就被立即拒绝,而不是排队等候,从而加速失败判定。
  • 回退机制:当请求失败、超时、被拒绝,或当断路器打开时,执行回退逻辑。回退逻辑可由开发人员自行提供,例如返回一个缺省值。
  • 包裹请求:使用HystrixCommand(或HystrixObservableCommand)包裹对依赖的调用逻辑,每个命令在独立线程中执行。这使用到了设计模式中的“命令模式”。
  • 监控:Hystrix可以近乎实时地监控运行指标和配置的变化,例如成功、失败、超时、以及被拒绝的请求等。

Feign默认已经整合了Hystrix,本节详细探讨Feign使用Hystrix的具体细节(项目中很少有单独使用Hystrix的)

Demo

加配置

# 默认fegin是不开启hystrix的支持的(开启全局启用)
feign.hystrix.enabled=true

编写接口并增加fallback方法

@FeignClient(name = "user-client", fallback = UserFeignClientFallback.class)
public interface UserFeignClient {
  @GetMapping("/users/{id}")
  User findById(@PathVariable("id") Long id);
}

@Component
class UserFeignClientFallback implements UserFeignClient {
  @Override
  public User findById(Long id) {
    return new User(id, "默认用户", "默认用户", 0, new BigDecimal(1));
  }
}

Hystris-局部启用

public class FeignDisableHystrixConfiguration {
    @Bean
    @Scope("prototype")
    public HystrixFeign.Builder feignBuilder() {
        return HystrixFeign.builder();
    }
}

Hystris-局部禁用

public class FeignDisableHystrixConfiguration {
    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder();
    }
}

在FeginClient中增加默认的配置

@FeignClient(name = "user-client", configuration = FeignDisableHystrixConfiguration.class)

相关配置

Execution相关参数详解

# 隔离策略,默认是Thread,可选Thread|Semaphore。thread用于线程池的隔离,一般适用于同步请求。semaphore是信号量模式,适用于异步请求
hystrix.command.default.execution.isolation.strategy 
# 命令执行超时时间,默认1000ms
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 
# 执行是否启用超时,默认启用true
hystrix.command.default.execution.timeout.enabled 
# 发生超时是是否中断,默认true
hystrix.command.default.execution.isolation.thread.interruptOnTimeout 
# 最大并发请求数,默认10,该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。
# 如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致
# 但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 

-----------------------------------------------------------------------------------------------------------------
ThreadPool 线程池配置

# 并发执行的核心线程数,默认10。不能设置为0,初始化setter的时候会出现异常。
hystrix.threadpool.default.coreSize 
#  并发执行的最大线程数,默认10。
hystrix.threadpool.default.maximumSize
# BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。
hystrix.threadpool.default.maxQueueSize 
#  队列截断阈值。即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,
# 请求也会被拒绝。如果maxQueueSize == -1,该字段将不起作用。
hystrix.threadpool.default.queueSizeRejectionThreshold
# 线程空闲存活时间。如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。
hystrix.threadpool.default.keepAliveTimeMinutes 
# 线程池统计指标的时间,默认10000。
hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds
# 将rolling window划分为n个buckets,默认10。
hystrix.threadpool.default.metrics.rollingStats.numBuckets 
-----------------------------------------------------------------------------------------------------------------
Circuit Breaker 熔断器配置

# 用来跟踪circuit的健康性,如果未达标则让request短路。默认true
hystrix.command.default.circuitBreaker.enabled
# 一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20 
hystrix.command.default.circuitBreaker.requestVolumeThreshold 
# 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内都会拒绝request,也就是5000毫秒后才会关闭circuit。默认5000
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
# 错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50,一般服务错误率达到10%时,服务已经不可用了,所以一般建议设置到10以下。 
hystrix.command.default.circuitBreaker.errorThresholdPercentage
# 强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
hystrix.command.default.circuitBreaker.forceOpen 
# 强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略circuitBreaker.errorThresholdPercentage
hystrix.command.default.circuitBreaker.forceClosed 
-----------------------------------------------------------------------------------------------------------------

Metrix 健康统计配置

# 设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。
# 若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,
# 每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
hystrix.command.default.metrics.rollingStats.timeInMilliseconds
# 设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,
# 那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
hystrix.command.default.metrics.rollingStats.numBuckets
# 执行时是否enable指标的计算和跟踪,默认true
hystrix.command.default.metrics.rollingPercentile.enabled
# 设置rolling percentile window的时间,默认60000
hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds
# 设置rolling percentile window的numberBuckets。逻辑同上。默认6
hystrix.command.default.metrics.rollingPercentile.numBuckets
# 如果bucket size=100,window=10s,若这10s里有500次执行,
# 只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
hystrix.command.default.metrics.rollingPercentile.bucketSize
# 记录health 快照(用来统计成功和错误绿)的间隔,默认500ms
hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 

-----------------------------------------------------------------------------------------------------------------

Fallback 降级配置(这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略 )

# 如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests  
# 当执行失败(run方法抛异常)或者请求被拒绝(资源不足),是否会尝试调用hystrixCommand.getFallback() 。默认true
hystrix.command.default.fallback.enabled 

-----------------------------------------------------------------------------------------------------------------


你可能感兴趣的:(SpringCloud-Hystrix-01入门介绍)