07.Spring Cloud 之 Hystrix

1. 概述

1.1 服务熔断
1.1.1 雪崩效应

在复杂的系统中,经常会出现 A 依赖于 B,B 依赖于 C,C 依赖于 D,…… 这种依赖将会产生很长的调用链路,这种复杂的调用链路称为 1-> N 的扇出。

如果在 A 的调用链路上某一个或几个被调用的子服务不可用或延迟较高,则会导致调用A 服务的请求被堵住。

堵住的 A 请求会消耗占用系统的线程、IO 等资源,当对 A 服务的请求越来越多,占用的计算机资源越来越多的时候,会导致系统瓶颈出现,造成其他的请求同样不可用,最终导致业务系统崩溃,这种现象称为雪崩效应。

1.1.2 熔断机制

熔断机制是服务雪崩的一种有效解决方案。当指定时间窗内的请求失败率达到设定阈值时,系统将通过断路器直接将此请求链路断开。常见的熔断有两种:

  • 预熔断

  • 即时熔断

1.2 服务降级

服务降级是请求发生问题后的一种增强用户体验的方式。

现代系统中,发生了服务熔断,一定会出现服务降级;发生了服务降级,不一定会发生服务熔断。

1.3 Hystrix 简介
1.3.1 概述

Hystrix 是一种开关装置,类似于熔断保险丝。在消费者端安装一个 Hystrix 熔断器,当 Hystrix 监控到某个服务发生故障后熔断器会开启,将此服务访问链路断开。不过 Hystrix 并不会将该服务的消费者阻塞,或向消费者抛出异常,而是向消费者返回一个符合预期的备选响应(FallBack)。通过 Hystrix 的熔断与降级功能,避免了服务雪崩的发生,同时也考虑到了用户体验。故 Hystrix 是系统的一种防御机制。

1.3.2 服务降级方式

Hystrix 对于服务降级的实现方式有两种:fallbackMethod 服务降级,与 fallbackFactory 服务降级。Hystrix 可以与 Feign 整合使用。

当一个服务同时存在类级别与方法级别的降级时,使用 fallbackMethod 方式则方法级别的降级优先级高,使用 fallback 方式则类级别的降级优先级高(即方法降级失效)

2. Hystrix 环境搭建

2.1 FallbackMethod 降级环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-cloud/tutorial-spring-cloud-consumer/tutorial-spring-cloud-consumer-hystrix-fallbackmethod-6005 工程

2.1.1 配置文件
1. pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
2. application.properties
# 端口号
server.port=6005
2.1.2 核心代码
1. ConsumerApplication6005

这里使用 @SpringCloudApplication 注解,它包含了 @SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreaker

@SpringCloudApplication
public class ConsumerApplication6005 {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication6005.class, args);
    }

}
2. ConsumerController
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @RequestMapping("/info")
    @HystrixCommand(fallbackMethod = "infoFallback")
    public Map<String, String> info(String id) {
        throw new RuntimeException("故意报错了:" + id);
    }

    public Map<String, String> infoFallback(String id) {
        Map<String, String> result = new HashMap<>(10);
        result.put("id", id);
        result.put("message", "方法降级了");
        return result;
    }

}
2.2 通过 FallBack 整合 Feign 环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-cloud/tutorial-spring-cloud-consumer/tutorial-spring-cloud-consumer-feign-hystrix-fallback-6006 工程

2.2.1 配置文件
1. pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
2. application.properties
# 端口号
server.port=6006
# 此实例注册到 eureka 服务端的 name
spring.application.name=tutorial-spring-cloud-consumer-feign-hystrix-fallback
# 指定 eureka 服务注册中心地址
eureka.client.service-url.defaultZone=http://localhost:7001/eureka
# 此实例注册到 eureka 服务端的唯一的实例 ID
eureka.instance.instance-id=tutorial-spring-cloud-consumer-feign-hystrix-fallback-6006
# 是否显示 IP 地址
eureka.instance.prefer-ip-address=true
# eureka 客户需要多长时间发送心跳给 eureka 服务器,表明它仍然活着,默认为 30 秒
eureka.instance.lease-renewal-interval-in-seconds=10
# eureka 服务器在接收到实例的最后一次发出的心跳后,需要等待多久才可以将此实例删除,默认为 90 秒
eureka.instance.lease-expiration-duration-in-seconds=30
# 设置 info 信息
info.app.name=tutorial-spring-cloud-consumer-feign-hystrix-fallback
# feign 客户端默认连接超时
feign.client.config.default.connect-timeout=5000
# feign 客户端默认读取超时
feign.client.config.default.read-timeout=5000
# feign 组件支持 Hystrix
feign.hystrix.enabled=true
2.2.2 核心代码
1. ConsumerApplication6006
@SpringCloudApplication
@EnableFeignClients
public class ConsumerApplication6006 {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication6006.class, args);
    }

}
2. ProviderFeign
@FeignClient(value = "tutorial-spring-cloud-provider-eureka", fallback = ProviderFeignFallback.class)
@RequestMapping("/provider")
public interface ProviderFeign {

    @RequestMapping("/info")
    Map<String, String> info();
}
3. ProviderFeignFallback
@Component
@RequestMapping("/fallback/provider")
public class ProviderFeignFallback implements ProviderFeign {

    @Override
    public Map<String, String> info() {
        Map<String, String>  result = new HashMap<>(10);
        result.put("code", "100");
        result.put("msg", "前方拥堵");
        return result;
    }

}
2.3 通过 FallBackFactory 整合 Feign 环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-cloud/tutorial-spring-cloud-consumer/tutorial-spring-cloud-consumer-feign-hystrix-fallbackfactory-6007 工程

2.3.1 配置文件
1. pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
2. application.properties
# 端口号
server.port=6007
# 此实例注册到 eureka 服务端的 name
spring.application.name=tutorial-spring-cloud-consumer-feign-hystrix-fallbackfactory
# 指定 eureka 服务注册中心地址
eureka.client.service-url.defaultZone=http://localhost:7001/eureka
# 此实例注册到 eureka 服务端的唯一的实例 ID
eureka.instance.instance-id=tutorial-spring-cloud-consumer-feign-hystrix-fallbackfactory-6007
# 是否显示 IP 地址
eureka.instance.prefer-ip-address=true
# eureka 客户需要多长时间发送心跳给 eureka 服务器,表明它仍然活着,默认为 30 秒
eureka.instance.lease-renewal-interval-in-seconds=10
# eureka 服务器在接收到实例的最后一次发出的心跳后,需要等待多久才可以将此实例删除,默认为 90 秒
eureka.instance.lease-expiration-duration-in-seconds=30
# 设置 info 信息
info.app.name=tutorial-spring-cloud-consumer-feign-hystrix-fallbackfactory
# feign 客户端默认连接超时
feign.client.config.default.connect-timeout=5000
# feign 客户端默认读取超时
feign.client.config.default.read-timeout=5000
# feign 组件支持 Hystrix
feign.hystrix.enabled=true
2.3.2 核心代码
1. ProviderFeign
@FeignClient(value = "tutorial-spring-cloud-provider-eureka", fallbackFactory = ProviderFeignFallbackFactory.class)
@RequestMapping("/provider")
public interface ProviderFeign {

    @RequestMapping("/info")
    Map<String, String> info();
}
2. ProviderFeignFallbackFactory
@Component
public class ProviderFeignFallbackFactory implements FallbackFactory<ProviderFeign> {
    @Override
    public ProviderFeign create(Throwable throwable) {
        return new ProviderFeign() {
            @Override
            public Map<String, String> info() {
                Map<String, String> result = new HashMap<>(10);
                result.put("code", "100");
                result.put("msg", "前方拥堵");
                return result;
            }
        };
    }

}

3. Hystrix Dashboard 环境搭建

3.1 应用环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-cloud/tutorial-spring-cloud-consumer/tutorial-spring-cloud-consumer-feign-hystrix-dashboard-6008 工程

3.1.1 配置文件
1. pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
2. application.properties
# 端口号
server.port=6008
# 此实例注册到 eureka 服务端的 name
spring.application.name=tutorial-spring-cloud-consumer-feign-hystrix-dashboard
# 指定 eureka 服务注册中心地址
eureka.client.service-url.defaultZone=http://localhost:7001/eureka
# 此实例注册到 eureka 服务端的唯一的实例 ID
eureka.instance.instance-id=tutorial-spring-cloud-consumer-feign-hystrix-dashboard-6008
# 是否显示 IP 地址
eureka.instance.prefer-ip-address=true
# eureka 客户需要多长时间发送心跳给 eureka 服务器,表明它仍然活着,默认为 30 秒
eureka.instance.lease-renewal-interval-in-seconds=10
# eureka 服务器在接收到实例的最后一次发出的心跳后,需要等待多久才可以将此实例删除,默认为 90 秒
eureka.instance.lease-expiration-duration-in-seconds=30
# 设置 info 信息
info.app.name=tutorial-spring-cloud-consumer-feign-hystrix-dashboard
# feign 客户端默认连接超时
feign.client.config.default.connect-timeout=5000
# feign 客户端默认读取超时
feign.client.config.default.read-timeout=5000
# feign 组件支持 Hystrix
feign.hystrix.enabled=true
# 开启健康检查
management.endpoints.web.exposure.include=*
3.2 Dashboard 环境搭建

代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见 tutorial-spring-cloud/tutorial-spring-cloud-consumer/tutorial-spring-cloud-dashboard-hystrix-8001 工程

3.2.1 配置文件
1. pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
2. application.properties
# 端口号
server.port=8001
3.2.2 核心代码
1. HystrixDashboardApplication8001
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication8001 {

    public static void main(String [] args){
        SpringApplication.run(HystrixDashboardApplication8001.class, args);
    }

}
3.3 查看监控效果

请求 http://localhost:6008/actuator ,可以看到所有的端点信息,其中 hystrix.stream 的地址是 http://localhost:6008/actuator/hystrix.stream

打开 http://localhost:8001/hystrix ,输入 http://localhost:6008/actuator/hystrix.stream 地址,即可查看监控信息

4. Hystrix 属性配置

详细参考文档 https://github.com/Netflix/Hystrix/wiki/Configuration

4.1 Execution
# 隔离策略,默认是 Thread,可选 Thread|Semaphor
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
# semaphore 应该占整个容器(tomcat)的线程池的一小部分。 Fallback 相关的属性这些参数可以应用于 Hystrix 的 THREAD 和 SEMAPHORE 策略
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests

# 如果并发数达到该设置值,请求会被拒绝和抛出异常并且 fallback 不会被调用。默认 10
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests

# 当执行失败或者请求被拒绝,是否会尝试调用
hystrix.command.default.fallback.enabled
4.2 Fallback
# 若采用信号量执行隔离策略,则可通过以下属性修改信号量的数量,即对某一依赖所允许的请求的最高并发量
fallback.isolation.semaphore.maxConcurrentRequests

# 默认 true
fallback.enabled
4.3 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
hystrix.command.default.circuitBreaker.errorThresholdPercentage

# 强制打开熔断器,如果打开这个开关,那么拒绝所有 request,默认 false
hystrix.command.default.circuitBreaker.forceOpen

# 强制关闭熔断器,如果这个开关打开,circuit 将一直关闭且忽略 circuitBreaker.errorThresholdPercentage
hystrix.command.default.circuitBreaker.forceClosed
4.4 Metrics
# 设置统计的时间窗口值的,毫秒值,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
4.5 Request Context
# 默认 true,需要重载 getCacheKey(),返回 null 时不缓存
hystrix.command.default.requestCache.enabled

# 记录日志到 HystrixRequestLog,默认 true
hystrix.command.default.requestLog.enabled
4.6 Collapser Properties
# 单次批处理的最大请求数,达到该数量触发批处理,默认 Integer.MAX_VALU
hystrix.collapser.default.maxRequestsInBatch

# 触发批处理的延迟,也可以为创建批处理的时间 + 该值,默认 10
hystrix.collapser.default.timerDelayInMilliseconds

# 是否对 HystrixCollapser.execute() and HystrixCollapser.queue() 的 cache,默认 true
hystrix.collapser.default.requestCache.enabled
4.7 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 个线程激活来提供服务

# 默认 10
hystrix.threadpool.default.coreSize

# 默认 10
hystrix.threadpool.default.maximumSize

# BlockingQueue 的最大队列数,当设为 -1,会使用 SynchronousQueue
# 值为正时使用 LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改 threadpool 的 queue size,除非 reinitialising thread executor。默认-1。
hystrix.threadpool.default.maxQueueSize

# 即使maxQueueSize没有达到,达到 queueSizeRejectionThreshold 该值后,请求也会被拒绝。因为 maxQueueSize 不能被动态修改,这个参数将允 许我们动态设置该值。
# if maxQueueSize ==1,该字段将不起作用 hystrix.threadpool.default.keepAliveTimeMinutes。如果 corePoolSize 和 maxPoolSize 设成一样(默认 实现)该设置无效。
# 如果通过 plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认 1
hystrix.threadpool.default.queueSizeRejectionThreshold

# 单位是分钟,默认值是 1
hystrix.threadpool.default.keepAliveTimeMinutes

# 默认值是 false
hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize

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

# 将 rolling window 划分为 n 个 buckets,默认 10
hystrix.threadpool.default.metrics.rollingStats.numBuckets
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值