当微服务系统的一个服务出现故障时,故障会沿着服务的调用链路在系统中疯狂蔓延,最终导致整个微服务系统的瘫痪,这就是“雪崩效应”。为了防止此类事件的发生,微服务架构引入了“熔断器”的一系列服务容错和保护机制。

它提供了熔断器功能,能够有效地阻止分布式微服务系统中出现联动故障,以提高微服务系统的弹性。Spring Cloud Hystrix 具有服务降级、服务熔断、线程隔离、请求缓存、请求合并以及实时故障监控等强大功能。

Hystrix [hɪst'rɪks],中文含义是豪猪,豪猪的背上长满了棘刺,使它拥有了强大的自我保护能力。而 Spring Cloud Hystrix 作为一个服务容错与保护组件,也可以让服务拥有自我保护的能力,因此也有人将其戏称为“豪猪哥”。

  • 保护线程资源:防止单个服务的故障耗尽系统中的所有线程资源。
  • 快速失败机制:当某个服务发生了故障,不让服务调用方一直等待,而是直接返回请求失败。
  • 提供降级(FallBack)方案:在请求失败后,提供一个设计好的降级方案,通常是一个兜底方法,当请求失败后即调用该方法。
  • 防止故障扩散:使用熔断机制,防止故障扩散到其他服务。
  • 监控功能:提供熔断器故障监控组件 Hystrix Dashboard,随时监控熔断器的状态。

降级

  1. pom.xml引入依赖

    <!--        hystrix-->
    <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
  2. 启动类加@EnableHystrix注解,开启hystrix

  3. 方法上加@HystrixCommand(fallbackMethod = "fallback") ,然后编写fallback方法

超时

# 全局超时时间
# 未设置Hystrix的超时时间时, 会有个默认的超时时间1秒, 设置后会覆盖掉1秒超时的默认设置
# ribbon 的超时时间和hystrix的超时时间会同时生效
# 实际超时时间会取最小的超时时间

feign.hystrix.enabled=true

ribbon.ReadTimeout=5000
ribbon.ConnectTimeout=5000

hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
/**
 * ------------------------ Hystrix 降级 --------------------------------- <br>
 * Hystrix 降级:当服务调用失败时,调用 Hystrix 的 fallback 方法,返回默认的数据 <br>
 * 这个方法可以写在本地,也可以写在远程。 <br>
 */
@HystrixCommand(fallbackMethod = "test03Fallback")
@GetMapping("/test03")
public Result test03() {
    StaticLog.info("reception 通过 openFeign 调用 goods 服务 test03");
    return testRemoteClient.test03();
}

public Result test03Fallback() {
    StaticLog.info("test03Fallback,被降级了");
    return Result.failure("服务器繁忙,请稍后再试");
}


/**
 * ------------------------ Hystrix 超时降级 --------------------------------- <br>
 * 因为设置了全局超时时间,test03会sleep(2000),而全局超时是5000,上面那个方法不会被降级 <br>
 * 这个方法单独写了超时时间1000,会取最小的超时时间,所以这个方法会超时
 */
@HystrixCommand(fallbackMethod = "test04Fallback", commandProperties = {
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})
@GetMapping("/test04")
public Result test04() {
    StaticLog.info("reception test04 通过 openFeign 调用 goods 服务 test03");
    return testRemoteClient.test03();
}

public Result test04Fallback() {
    StaticLog.info("test04Fallback,超时被降级了");
    return Result.failure("服务器繁忙,请稍后再试");
}

异常

/**
 * ------------------------ Hystrix 异常降级 --------------------------------- <br>
 * hystrix默认方法异常会自动降级,如果需要异常处理,直接在降价方法上加Throwable形参即可
 */
@HystrixCommand(fallbackMethod = "test05Fallback")
@GetMapping("/test05")
public Result test05() {
    StaticLog.info("reception test05 通过 openFeign 调用 goods 服务 test05");
    return testRemoteClient.test05();
}

public Result test05Fallback(Throwable throwable) {
    throwable.printStackTrace();
    StaticLog.error("test05Fallback,异常被降级了:[{}]", ExceptionUtil.getMessage(throwable));
    return Result.failure("服务器异常,请稍后再试");
}

/**
 * ------------------------ Hystrix 忽略异常 --------------------------------- <br>
 * 异常交给远程服务处理,不需要降级
 */
@HystrixCommand(fallbackMethod = "test06Fallback", ignoreExceptions = Throwable.class)
@GetMapping("/test06")
public Result test06() {
    StaticLog.info("reception test06 通过 openFeign 调用 goods 服务 test05");
    return testRemoteClient.test05();
}

public Result test06Fallback(Throwable throwable) {
    throwable.printStackTrace();
    StaticLog.error("test06Fallback,异常被降级了:[{}]", ExceptionUtil.getMessage(throwable));
    return Result.failure("服务器异常,请稍后再试");
}

如果远程服务有一个异常抛出后我们不希望进入到服务降级方法中去处理,而是直接将异常抛给用户,那么我们可以在@HystrixCommand 注解中添加忽略异常,如下:

@HystrixCommand(fallbackMethod = "fallback", ignoreExceptions=Throwable.class)

限流

/**
 * ------------------------ Hystrix 限流降级 --------------------------------- <br>
 * threadPoolKey:线程池唯一标识 <br>
 * coreSize:线程池核心线程数 <br>
 * maxQueueSize:线程池最大队列数 <br>
 */
@HystrixCommand(fallbackMethod = "test07Fallback",
                threadPoolKey = "goods",
                threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "2"),
                    @HystrixProperty(name = "maxQueueSize", value = "1")
                }
               )
@GetMapping("/test07")
public Result test07() {
    StaticLog.info("reception test07 通过 openFeign 调用 goods 服务 test03");
    return testRemoteClient.test03();
}

public Result test07Fallback() {
    StaticLog.error("test07Fallback,被降级了");
    return Result.failure("服务器限流,请稍后再试");
}

hystrix相关配置

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.maxConcurrentRequest如果并发数达到该设置值,请求会被拒绝和抛出异常并且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

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,那么公式是: 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使用自定义 实现,该设置才有用,默认1.

hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds 线程池统计指标的时间,默 认10000

hystrix.threadpool.default.metrics.rollingStats.numBuckets 将rolling window划分为n个 buckets,默认10

服务熔断

熔断机制是为了应对雪崩效应而出现的一种微服务链路保护机制。

当微服务系统中的某个微服务不可用或响应时间太长时,为了保护系统的整体可用性,熔断器会暂时切断请求对该服务的调用,并快速返回一个友好的错误响应。这种熔断状态不是永久的,在经历了一定的时间后,熔断器会再次检测该微服务是否恢复正常,若服务恢复正常则恢复其调用链路。

熔断状态

在熔断机制中涉及了三种熔断状态:

  • 熔断关闭状态(Closed):当务访问正常时,熔断器处于关闭状态,服务调用方可以正常地对服务进行调用。
  • 熔断开启状态(Open):默认情况下,在固定时间内接口调用出错比率达到一个阈值(例如 50%),熔断器会进入熔断开启状态。进入熔断状态后,后续对该服务的调用都会被切断,熔断器会执行本地的降级(FallBack)方法。
  • 半熔断状态(Half-Open): 在熔断开启一段时间之后,熔断器会进入半熔断状态。在半熔断状态下,熔断器会尝试恢复服务调用方对服务的调用,允许部分请求调用该服务,并监控其调用成功率。如果成功率达到预期,则说明服务已恢复正常,熔断器进入关闭状态;如果成功率仍旧很低,则重新进入熔断开启状态。

三种熔断状态之间的转化关系图:

image-20220511124607933

熔断机制

Hystrix 实现服务熔断的步骤如下:

  1. 当服务的调用出错率达到或超过 Hystix 规定的比率(默认为 50%)后,熔断器进入熔断开启状态。
  2. 熔断器进入熔断开启状态后,Hystrix 会启动一个休眠时间窗,在这个时间窗内,该服务的降级逻辑会临时充当业务主逻辑,而原来的业务主逻辑不可用。
  3. 当有请求再次调用该服务时,会直接调用降级逻辑快速地返回失败响应,以避免系统雪崩。
  4. 当休眠时间窗到期后,Hystrix 会进入半熔断转态,允许部分请求对服务原来的主业务逻辑进行调用,并监控其调用成功率。
  5. 如果调用成功率达到预期,则说明服务已恢复正常,Hystrix 进入熔断关闭状态,服务原来的主业务逻辑恢复;否则 Hystrix 重新进入熔断开启状态,休眠时间窗口重新计时,继续重复第 2 到第 5 步。

熔断案例

//Hystrix 熔断案例
@Override
@HystrixCommand(fallbackMethod = "deptCircuitBreaker_fallback", commandProperties = {
        //以下参数在 HystrixCommandProperties 类中有默认配置
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //是否开启熔断器
    	@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "1000"), //统计时间窗
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //统计时间窗内请求次数
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //休眠时间窗口期
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), //在统计时间窗口期以内,请求失败率达到 60% 时进入熔断状态
})
public String deptCircuitBreaker(Integer id) {
    if (id < 0) {
        //当传入的 id 为负数时,抛出异常,调用降级方法
        throw new RuntimeException("id 不能是负数!");
    }
    String serialNum = IdUtil.simpleUUID();
    return Thread.currentThread().getName() + "\t" + "调用成功,流水号为:" + serialNum;
}

//deptCircuitBreaker 的降级方法
public String deptCircuitBreaker_fallback(Integer id) {
    return "id 不能是负数,请稍后重试!\t id:" + id;
}

参数

参数 描述
metrics.rollingStats.timeInMilliseconds 统计时间窗。
circuitBreaker.sleepWindowInMilliseconds 休眠时间窗,熔断开启状态持续一段时间后,熔断器会自动进入半熔断状态,这段时间就被称为休眠窗口期。
circuitBreaker.requestVolumeThreshold 请求总数阀值。 在统计时间窗内,请求总数必须到达一定的数量级,Hystrix 才可能会将熔断器打开进入熔断开启转态,而这个请求数量级就是 请求总数阀值。Hystrix 请求总数阈值默认为 20,这就意味着在统计时间窗内,如果服务调用次数不足 20 次,即使所有的请求都调用出错,熔断器也不会打开。
circuitBreaker.errorThresholdPercentage 错误百分比阈值。 当请求总数在统计时间窗内超过了请求总数阀值,且请求调用出错率超过一定的比例,熔断器才会打开进入熔断开启转态,而这个比例就是错误百分比阈值。错误百分比阈值设置为 50,就表示错误百分比为 50%,如果服务发生了 30 次调用,其中有 15 次发生了错误,即超过了 50% 的错误百分比,这时候将熔断器就会打开。

服务监控

创建项目,改pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

然后配置端口

hystrix.dashboard.proxy-stream-allow-list=*

启动类加@EnableHystrixDashboard注解

启动服务

要监控的项目pom.xml加依赖

<!--        actuator-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

暴露端点

management.endpoints.web.exposure.include=*

也可以只暴露

management.endpoints.web.exposure.include=hystrix.stream

访问

http://localhost:11002/actuator/hystrix.stream

image-20220511124154194

turbine

pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-turbine</artifactId>
</dependency>

配置

server.port=8740

eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka8761:8761/eureka/,http://eureka8762:8762/eureka/,http://eureka8763:8763/eureka/

turbine.app-config=SERVICE-RECEPTION
turbine.cluster-name-expression="default"

开启

@EnableTurbine

访问

http://localhost:8740/turbine.stream