04.Spring Cloud 之 Hystrix

1. 概述

1.1 分布式系统面临的问题
  • 复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地失败。

  • 如果某个微服务的调用响应时间过长或者不可用,对微服务的调用就会占用越来越多的系统资源,进而引起系统崩溃,这就是所谓的“雪崩效应”

1.2 Hystrix 是什么
  • Hystrix 是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix 能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性

  • “断路器”本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延、乃至雪崩。

1.3 服务熔断
  • 熔断机制是应对雪崩效应的一种微服务链路保护机制

  • 当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回“错误”的响应信息。当检测到该节点微服务调用响应正常后恢复调用链路。在 SpringCloud 框架里熔断机制通过 Hystrix 实现。Hystrix 会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是 5 秒内 20 次调用失败就会启动熔断机制。熔断机制的注解是 @HystrixCommand

2. Hystrix 使用

  • 项目已上传至 https://github.com/masteryourself/study-spring-cloud.git

2.1 masteryourself-user-5001 工程

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

<!-- eureka 已经集成了 ribbon,这里不需要再单独引入-->
<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>
2. application.properties
# 此实例注册到eureka服务端的 name
spring.application.name=masteryourself-user
# 端口号
server.port=5001

# 与 eureka server 交互的地址
eureka.client.service-url.defaultZone=http://masteryourself-eureka-7001.com:7001/eureka
# 此实例注册到 eureka 服务端的唯一的实例 ID
eureka.instance.instance-id=masteryourself-user-5001
# 是否显示 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

# 请求连接的超时时间,默认的时间为 1000 ms
ribbon.ConnectTimeout=3000
# 请求处理的超时时间
ribbon.ReadTimeout=3000

# 命令执行超时时间,默认1000 ms
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=2500
# 每个 window 的请求数量,默认为 20
hystrix.command.default.circuitBreaker.requestVolumeThreshold=5
2.1.2 代码
1. UserControllerWithHystrix
@RestController
public class UserControllerWithHystrix {

    private static final String ORDER_URL_PREFIX = "http://masteryourself-order";

    private static final String WALLET_URL_PREFIX = "http://masteryourself-wallet";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "doOrderByHystrix")
    @HystrixCommand(fallbackMethod = "hystrixFallbackMethod")
    public Map doOrderByHystrix() {
        return restTemplate.getForObject(ORDER_URL_PREFIX + "/doOrder", Map.class);
    }

    @RequestMapping(value = "doDeductByHystrix")
    @HystrixCommand(fallbackMethod = "hystrixFallbackMethod",
            threadPoolKey = "wallet",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "2"),
                    @HystrixProperty(name = "maxQueueSize", value = "1")}
    )
    public Map doDeductByHystrix() {
        System.out.println("请求进入");
        return restTemplate.getForObject(WALLET_URL_PREFIX + "/doDeduct", Map.class);
    }

    public Map hystrixFallbackMethod() {
        Map result = new HashMap(10);
        result.put("code", "330");
        result.put("msg", "前方拥堵");
        return result;
    }

}
2. UserApplication5001
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@RibbonClients({
        @RibbonClient(name = "MASTERYOURSELF-ORDER", configuration = OrderRuleConfig.class),
        @RibbonClient(name = "MASTERYOURSELF-WALLET", configuration = WalletRuleConfig.class)
})
@EnableHystrix
public class UserApplication5001 {

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

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

2.2 masteryourself-order 工程

2.2.1 代码
1. OrderController
@RestController
public class OrderController {

    @Autowired
    private Environment environment;

    private AtomicInteger count = new AtomicInteger(0);

    @RequestMapping(value = "doOrder")
    public Map<String, String> doOrder() {
        if (count.getAndIncrement() % 3 == 0) {
            throw new RuntimeException("下单报错了");
        }
        Map<String, String> result = new HashMap<>(10);
        result.put("code", "200");
        result.put("msg", "下单成功");
        result.put("info", environment.getProperty("eureka.instance.instance-id"));
        return result;
    }

}

2.3 masteryourself-wallet 工程

2.3.1 代码
1. WalletController
@RestController
public class WalletController {

    @Autowired
    private Environment environment;

    @RequestMapping(value = "doDeduct")
    public Map<String, String> doDeduct() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, String> result = new HashMap<>(10);
        result.put("code", "200");
        result.put("msg", "扣款成功");
        result.put("info", environment.getProperty("eureka.instance.instance-id"));
        return result;
    }

}
2.4 效果展示
  • 多次请求 http://192.168.20.1:5001/doOrderByHystrix ,每台服务器每隔 3 次就会抛出 RuntimeException,然后被降级方法拦截到,返回降级结果

在这里插入图片描述

  • 多次请求 http://192.168.20.1:5001/doDeductByHystrix ,只要每秒中发出超过四个请求,第四个请求就会被进入降级方法

在这里插入图片描述

3. Feign 整合 Hystrix 使用

  • 项目已上传至 https://github.com/masteryourself/study-spring-cloud.git
3.1 配置文件
1. application.properties
# 此实例注册到eureka服务端的 name
spring.application.name=masteryourself-user
# 端口号
server.port=5001

# 与 eureka server 交互的地址
eureka.client.service-url.defaultZone=http://masteryourself-eureka-7001.com:7001/eureka
# 此实例注册到 eureka 服务端的唯一的实例 ID
eureka.instance.instance-id=masteryourself-user-5001
# 是否显示 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

# 请求连接的超时时间,默认的时间为 1000 ms
ribbon.ConnectTimeout=3000
# 请求处理的超时时间
ribbon.ReadTimeout=3000
        
# 命令执行超时时间,默认1000 ms
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=2500
# 每个 window 的请求数量,默认为 20
hystrix.command.default.circuitBreaker.requestVolumeThreshold=5

# feign 组件支持 hystrix
feign.hystrix.enabled=true
3.2 代码
1. OrderService
@FeignClient(value = "MASTERYOURSELF-ORDER",fallback = OrderServiceFallback.class)
public interface OrderService {

    @RequestMapping(value = "doOrder")
    Map<String, String> doOrder();

}
2. OrderServiceFallback
@Component
public class OrderServiceFallback implements OrderService {

    @Override
    public Map<String, String> doOrder() {
        Map result = new HashMap(10);
        result.put("code","400");
        result.put("msg","order 服务降级了");
        return result;
    }

}
3. UserControllerWithFeignAndHystrix
@RestController
public class UserControllerWithFeignAndHystrix {

    @Autowired
    private OrderService orderService;

    @RequestMapping(value = "doOrderByFeignAndHystrix")
    public Map doOrderByFeignAndHystrix() {
        return orderService.doOrder();
    }

    public Map hystrixFallbackMethod() {
        Map result = new HashMap(10);
        result.put("code", "330");
        result.put("msg", "前方拥堵");
        return result;
    }

}
3.3 效果展示
  • OrderService 是 Feign 组件,同时指明了 fallback 处理类,OrderServiceFallback 实现 OrderService 接口,实现里面重写降级方案

  • 多次请求 http://192.168.20.1:5001/doOrderByFeignAndHystrix ,每台服务器每隔 3 次就会抛出 RuntimeException,然后被降级方法拦截到,返回降级结果

在这里插入图片描述

4. Hystrix 相关配置

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

# 默认 true
hystrixCommand.getFallback()
4.2 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.3 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.4 Request Context 相关参数
# 默认 true,需要重载 getCacheKey(),返回 null 时不缓存
hystrix.command.default.requestCache.enabled

# 记录日志到 HystrixRequestLog,默认 true
hystrix.command.default.requestLog.enabled
4.5 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.6 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

# 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

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

# 将 rolling window 划分为 n 个 buckets,默认 10
hystrix.threadpool.default.metrics.rollingStats.numBuckets
发布了37 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/masteryourself/article/details/103101864
今日推荐