SpringCloud Hystrix详解

一、Hystrix介绍

1、分布式系统面临问题

多个微服务之间调用的时候,假如微服务A调用微服务B和微服务C,微服务B和微服务C又调用其他的微服务,这就是所谓的"扇出"。

如果扇出的链路上某个微服务的调用响应的时间过长或者不可用,对微服A的调用就会占用越来越多的系统资源,进而引起系统崩溃,即"雪崩效应"。

对于高流量的应用来说,单一的后端依赖可能会导致所有的服务器上的所有资源都在几秒钟内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障。这些都表示需要对故障和延迟进行隔离和管理,以便单个依赖关系的失败,不能取消整个应用程序或系统。
所以,通常当你发现一个模块下的某个实例失败后,这时候这个模块依然还会接收流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫雪崩。

二、Hystrix概念

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

在微服务系统中,Hystrix 能够帮助我们实现以下目标:

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

Hystrix是一个用于处理分布式系统的延迟和容错的开源库,可以保证一个服务出现故障时,不会导致整个系统出现雪崩效应,以提高分布式系统弹性

②作为“断路器”,在一个服务出现故障时,可以通过短路器监控,返回一个可以处理的响应结果,保证服务调用线程不会长时间被占用,避免故障蔓延

三、Hystrix作用

(1)服务降级

服务出现故障时,给故障服务降级到事先准备好的故障处理结果,将此结果返回给服务消费者,如:客户端访问服务1,服务1调用服务2,服务2出现故障,Hystrix服务降级,返回一个可以处理的结果给服务1,服务1再以友好的错误界面返回给客户端。

在这里插入图片描述
Hystrix 提供了服务降级功能,能够保证当前服务不受其他服务故障的影响,提高服务的健壮性。

服务降级的使用场景有以下 2 种:

  • 在服务器压力剧增时,根据实际业务情况及流量,对一些不重要、不紧急的服务进行有策略地不处理或简单处理,从而释放服务器资源以保证核心服务正常运作。
  • 当某些服务不可用时,为了避免长时间等待造成服务卡顿或雪崩效应,而主动执行备用的降级逻辑立刻返回一个友好的提示,以保障主体业务不受影响。
    Hystrix的降级策略:

Hystrix提供了如下三种降级策略:

  • 熔断降级: 默认在10秒内,发送20次请求,失败率达到50%,就会触发熔断降级。

  • 超时降级: 默认请求的响应时间超过1秒,就会触发超时降级。

  • 资源隔离降级

    • 信号量隔离 调用线程与hystrixCommand线程是同一个线程。同步方式。资源消耗小。不支持超时。

    • 线程池隔离 调用线程与hystrixCommand线程不是同一个线程。异步方式。支持超时。可以为每个服务单独分配线程池。大量线程的上下文切换带来的开销比较大。

(2)服务熔断

熔断机制是应对服务雪崩的一种链路保护机制,当服务出现故障时,服务会进行降级,熔断该服务节点,迅速返回错误响应信息。当检测到服务访问正常时,恢复其链路节点

在这里插入图片描述

(3)服务隔离

服务隔离主要包括线程池隔离以及信号量隔离。

四 、服务降级和熔断的区别

目的不同:

  • 服务降级的主要目的是在面对异常情况时保障系统的可用性,通过减少非核心功能或服务的质量来维持核心功能的运行;
  • 熔断的主要目的是防止连续的服务故障对整个系统造成影响,通过中断对故障服务的请求来保护系统的稳定性,防止雪崩的发生。

触发条件不同:

  • 服务降级通常是基于系统整体的负载或异常情况触发;
    默认情况下,hystrix 在以下 4 种条件下都会触发降级机制:
    1. 方法抛出 HystrixBadRequestException
    2. 方法调用超时
    3. 熔断器开启拦截调用
    4. 线程池或队列或信号量已满

虽然 hystrix 组件的触发机制,不能代表所有的熔断和降级机制,但足矣说明此问题。

  • 熔断是基于某个服务的错误率,当错误率超出某个阈值时触发。
    默认情况 hystrix 如果检测到 10 秒内请求的失败率超过 50%,就触发熔断机制。之后每隔 5 秒重新尝试请求微服务,如果微服务不能响应,继续走熔断机制。如果微服务可达,则关闭熔断机制,恢复正常请求。
    在这里插入图片描述

执行方式不同:

  • 服务降级通过降低非核心功能的优先级或关闭一些服务来应对异常情况;
  • 熔断通过中断对故障服务的请求来切断对不稳定服务的访问,以防止连续故障的传播。

在实际应用中,服务降级和熔断通常结合使用,以提高整个系统的稳定性和可用性。

四、Hystrix配置实战

https://blog.csdn.net/qq_36944952/article/details/136070831

4.1 pom文件引入spring-boot-starter-netflix-hystrix

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

4.2 在启动类添加注解 @EnableCircuitBreaker 注解或者 @EnableHystrix 注解

@SpringBootApplication
@EnableCircuitBreaker
public class HystrixSpringApplication {
  
  public static void main(String[] args) {
    SpringApplication.run(HystrixSpringApplication.class, args);
  }
}

4.3.在controller中需要增加熔断功能的接口添加注解@HystrixCommand, 详细参数见 Hystrix参数

熔断降级配置、 超时降级配置、 资源隔离(线程池)触发降级配置、信号量资源隔离配置

4.3.1 熔断降级配置

 /**
     * 
     * 熔断降级测试
     * hystrixCircuitBreakHystrix  熔断降级测试
     * 通过opeFegin 测试请求接口+hystrix的降级测试
     * @return
     */
    @HystrixCommand(fallbackMethod = "circuitBreakHystrixFallback",groupKey = "breakHystrixTest",commandKey = "getcircuitBreakHystrixTest", commandProperties = {
            @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value = "true"),// 是否开启熔断器
            @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "20"),      // 统计时间窗内请求次数
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "50"),// 在统计时间窗内,失败率达到50%进入熔断状态
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "5000"), // 休眠时间窗口
            @HystrixProperty(name = HystrixPropertiesManager.METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, value = "10000") // 统计时间窗
    })
    public List<String> getcircuitBreakHystrixTest() {
        return configEnvServiceClient.getcircuitBreakHystrixTest();
    }

    public List<String> circuitBreakHystrixFallback() {
        return Arrays.asList("Fallback response  circuitBreakHystrixFallback");
    }

4.3.2 超时降级配置

 /**
     * 超时降级测试
     * @return
     */
    @HystrixCommand(fallbackMethod = "TimeoutBreakHystrixFallback",groupKey = "breakHystrixTest",commandKey = "getTimeoutBreakHystrixTest", commandProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_TIMEOUT_ENABLED, value = "true"),
            // 是否开启超时降级
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "5000"),
            // 请求的超时时间,默认10000
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT, value = "true")
            // 当请求超时时,是否中断线程,默认true
    })
    public List<String> getTimeoutBreakHystrixTest() {
        try {
            log.info("getTimeoutBreakHystrixTest start");
            Thread.sleep(7000);
            log.info("getTimeoutBreakHystrixTest end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return configEnvServiceClient.getBreakHystrixTest();
    }


    public List<String> timeoutBreakHystrixFallback() {
        return Arrays.asList("Fallback response  timeoutBreakHystrixFallback");
    }

4.3.3 资源隔离(线程池)触发降级配置

   /**
     * 资源隔离触发降级
     * @return
     */
    @HystrixCommand(fallbackMethod = "threadIsolationFallback",groupKey = "breakHystrixTest",commandKey = "getExecutionIsolation_strategyHystrixTest",commandProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "THREAD")
            },
            threadPoolProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.CORE_SIZE, value = "1"),
                    @HystrixProperty(name = HystrixPropertiesManager.MAX_QUEUE_SIZE, value = "-1"),
                    @HystrixProperty(name = HystrixPropertiesManager.QUEUE_SIZE_REJECTION_THRESHOLD, value = "1"),
                    @HystrixProperty(name = HystrixPropertiesManager.KEEP_ALIVE_TIME_MINUTES, value = "1"),
            }
    )
    public List<String> getExecutionThreadIsolation_strategyHystrixTest() {
        try {
            log.info("getExecutionThreadIsolation_strategyHystrixTest start");
            Thread.sleep(10000);
            log.info("getExecutionThreadIsolation_strategyHystrixTest end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.error("begin log");
     //   return Arrays.asList("success response  isolationFallbackFallback");
        return configEnvServiceClient.getBreakHystrixTest();
    }

    public List<String> threadIsolationFallback() {
        log.error("FallbackFallback log");
        return Arrays.asList("Fallback response  threadIsolationFallback");
    }
  • coreSize:核心线程池的大小,默认值是 10,一般根据 QPS * 99% cost + redundancy count 计算得出。

  • allowMaximumSizeToDivergeFromCoreSize:是否允许线程池扩展到最大线程池数量,默认为 false;

  • maximumSize:线程池中线程的最大数量,默认值是 10,此配置项单独配置时并不会生效,需要启用 allowMaximumSizeToDivergeFromCoreSize 项。

  • maxQueueSize:作业队列的最大值,默认值为 -1,设置为此值时,队列会使用 SynchronousQueue,此时其 size 为0,Hystrix 不会向队列内存放作业。如果此值设置为一个正的 int 型,队列会使用一个固定 size 的 LinkedBlockingQueue,此时在核心线程池内的线程都在忙碌时,会将作业暂时存放在此队列内,但超出此队列的请求依然会被拒绝。

  • queueSizeRejectionThreshold:由于 maxQueueSize 值在线程池被创建后就固定了大小,如果需要动态修改队列长度的话可以设置此值,即使队列未满,队列内作业达到此值时同样会拒绝请求。此值默认是 5,所以有时候只设置了 maxQueueSize 也不会起作用。

  • keepAliveTimeMinutes:由上面的 maximumSize,我们知道,线程池内核心线程数目都在忙碌,再有新的请求到达时,线程池容量可以被扩充为到最大数量,等到线程池空闲后,多于核心数量的线程还会被回收,此值指定了线程被回收前的存活时间,默认为 2,即两分钟。

资源隔离(线程池)触发降级 妈的测试有点不生效
注意:资源隔离(线程池)触发降级 ,这种触发只有在降级方法,用到线程池请求的时候才会生效。比如,在请求方法中我们直接返回Arrays.asList(“success response isolationFallbackFallback”) 的时候不会触发降级方法isolationFallback。线程池配置2,测试当请求数大于线程池的线程数据量触发降级

在这里插入图片描述

4.3.4 信号量资源隔离配置

/**
     * 信号量资源隔触发降级降级
      */
    @HystrixCommand(fallbackMethod = "semaphoreisolationFallback",
            commandProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "SEMAPHORE"),
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "2")
            }
    )
    public List<String> getSemaphoreIsolation_strategyHystrixTest() {
        try {
            log.info("getSemaphoreIsolation_strategyHystrixTest start");
            Thread.sleep(10000);
            log.info("getSemaphoreIsolation_strategyHystrixTest end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.error("begin log");
        //   return Arrays.asList("success response  isolationFallbackFallback");
        return configEnvServiceClient.getBreakHystrixTest();
    }

    public List<String> semaphoreisolationFallback() {
        log.error("FallbackFallback log");
        return Arrays.asList("Fallback response  threadIsolationFallback");
    }

在这里插入图片描述

@RestController
@RequestMapping("hystrix")
public class HystrixController {

    @Autowired
    private HystrixService hystrixService;
    
    // 熔断降级
    @GetMapping("{num}")
    @HystrixCommand(fallbackMethod="circuitBreakerFallback", commandProperties = {
            @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value = "true"),
            // 是否开启熔断器
            @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "20"),      // 统计时间窗内请求次数
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "50"),// 在统计时间窗内,失败率达到50%进入熔断状态
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "5000"), // 休眠时间窗口
            @HystrixProperty(name = HystrixPropertiesManager.METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, value = "10000") // 统计时间窗
    })
    public String testCircuitBreaker(@PathVariable Integer num, @RequestParam String name) {
        if (num % 2 == 0) {
            return "请求成功";
        } else {
            throw RunTimeException("");
        }
    }

  	// fallback方法的参数个数、参数类型、返回值类型要与原方法对应,fallback方法的参数多加个Throwable
    public String circuitBreakerFallback(Integer num, String name) {
        return "请求失败,请稍后重试";
    }
    
    // 超时降级
    @GetMapping
    @HystrixCommand(fallbackMethod = "timeoutFallback", commandProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_TIMEOUT_ENABLED, value = "true"),
            // 是否开启超时降级
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "10000"),
            // 请求的超时时间,默认10000
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT, value = "true")
            // 当请求超时时,是否中断线程,默认true
    })
    public String testTimeout(@RequestParam String name) throws InterruptedException{
        Thread.sleep(200)
        return "success";
    }

    public String timeoutFallback(String name) {
        return "请求超时,请稍后重试";
    }
    
    // 资源隔离(线程池)触发降级
    @GetMapping("isolation/threadpool")
    @HystrixCommand(fallbackMethod = "isolationFallback",
            commandProperties = {
               		@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "THREAD")
            },
            threadPoolProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.CORE_SIZE, value = "10"),
                    @HystrixProperty(name = HystrixPropertiesManager.MAX_QUEUE_SIZE, value = "-1"),
                    @HystrixProperty(name = HystrixPropertiesManager.QUEUE_SIZE_REJECTION_THRESHOLD, value = "2"),
                    @HystrixProperty(name = HystrixPropertiesManager.KEEP_ALIVE_TIME_MINUTES, value = "1"),
            }
    )
    public String testThreadPoolIsolation(@RequestParam String name) throws InterruptedException {
        Thread.sleep(200)
        return "success";
    }

    public String isolationFallback(String name) {
        return "资源隔离拒绝,请稍后重试";
    }
    
    // 信号量资源隔离
    @GetMapping("isolation/semaphore")
    @HystrixCommand(fallbackMethod = "isolationFallback",
            commandProperties = {
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY, value = "SEMAPHORE"),
                    @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "2")
            }
    )
    public String testSemaphoreIsolation(@RequestParam String name) throws InterruptedException {
        Thread.sleep(200)
        return "success";
    }

    public String isolationFallback(String name) {
        return "资源隔离拒绝,请稍后重试";
    }
  
}


4.4 全局参数application.yml

@HystrixCommand注解的配置优先于Hystrix全局配置

hystrix:
    command:
        default:
            circuitBreaker:
                enabled: true
                requestVolumeThreshold: 20
                errorThresholdPercentage: 50
                sleepWindowInMilliseconds: 5000
            execution:
                timeout:
                    enabled: true
                isolation:
                    thread:
                        timeoutInMilliseconds: 2000
                        interruptOnTimeout: true
                    semaphore:
                        maxConcurrentRequests: 10
                    strategy: THREAD
            metrics:
                rollingStats:
                    timeInMilliseconds: 10000
    threadpool:
        default:
            coreSize: 10
            maximumSize: 19
            allowMaximumSizeToDivergeFromCoreSize: false
            keepAliveTimeMinutes: 1
            maxQueueSize: -1
            queueSizeRejectionThreshold: 5

五、OpenFeign Hystrix

在服务提供方定义 feign client 接口 以及 fallback或者fallbackFactory,在服务消费方定义具体的降级策略。

5.1.引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclinet</artifactId>
    <version>9.7.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-hystrix</artifactId>
    <version>9.7.0</version>
</dependency>

5.2.定义Feign调用接口,其中fallbackFactory中为试下的fallback方法

// fallbackFactory 实现
@FeignClient(value = "hystrixProject", url="http://localhost:8085", fallbackFactory = HystrixServerFallbackFactory.class)
public interface HystrixServer {
    @GetMapping("/test")
    String test();
}

// fallback 实现
@FeignClient(value = "hystrixProject", url="http://localhost:8085", fallback = HystrixServerFallback.class)
public interface HystrixServer {
    @GetMapping("/test")
    String test();
}

5.3.定义HystrixServerFallbackFactory.class

import feign.hystrix.FallbackFactory;

@Component
public class HystrixServerFallbackFactory implements FallbackFactory<HystrixServer> {
    
    @Override
    public HystrixServer create(Throwable throwable) {
        return new HystrixServer() {
            @Override
            public String test() {
                return "服务降级";
            }
        }
    }
}

5.4.定义HystrixServerFallback.class

@Component
public class HystrixServerFallback implements HystrixServer {
    public String test() {
        return "服务降级";
    }
}

5.5.全局配置,application.yml

老版本配置:对应于本文的版本

feign:
    hystrix:
        enabled: true

新版本配置:

feign:
  circuitbreaker:
    enabled: true    //开启服务降级

6.启动类增加注解

@SpringBootApplication
@EnableFeignClients
public class HystrixDashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardApplication.class, args);
    }
}

六、Hystrix参数

HystrixCommand.Setter核心参数

  • HystrixCommandGroupKey:区分一组服务,一般以接口为粒度。
  • HystrixCommandKey:区分一个方法,一般以方法为粒度。
  • HystrixThreadPoolKey:一个HystrixThreadPoolKey下的所有方法共用一个线程池。
  • HystrixCommandProperties:基本配置

Command Properties

  • hystrix.command.default.execution.isolation.strategy 隔离策略,默认是Thread,可选Thread|Semaphore。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。
  • hystrix.command.default.execution.isolation.thread.interruptOnCancel

Fallback降级配置

这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略

  • hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10.
  • hystrix.command.default.fallback.enabled 当执行失败(run方法抛异常)或者请求被拒绝(资源不足),是否会尝试调用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,一般服务错误率达到10%时,服务已经不可用了,所以一般建议设置到10以下。
  • hystrix.command.default.circuitBreaker.forceOpen 强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false.
  • hystrix.command.default.circuitBreaker.forceClosed 强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略circuitBreaker.errorThresholdPercentage

Metrix 健康统计配置

  • 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() andHystrixCollapser.queue()的cache,默认true

ThreadPool线程池配置

  • hystrix.threadpool.default.coreSize 并发执行的核心线程数,默认10。不能设置为0,初始化setter的时候会出现异常。

  • hystrix.threadpool.default.maximumSize 并发执行的最大线程数,默认10。 This property sets the maximum thread-pool size. This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize. Prior to 1.5.9, core and maximum sizes were always equal.

  • hystrix.threadpool.default.maxQueueSize BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。Note: This property only applies at initialization time since queue implementations cannot be resized or changed without re-initializing the thread executor which is not supported.

  • hystrix.threadpool.default.queueSizeRejectionThreshold 队列截断阈值。即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。如果maxQueueSize == -1,该字段将不起作用。

  • hystrix.threadpool.default.keepAliveTimeMinutes 线程空闲存活时间。如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。

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

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

建议设置值:

  • timeoutInMilliseconds:依赖外部接口时,推荐配置比rpc超时时间稍短,否则可能无法发挥作用。
  • maxConcurrentRequests:估算值:(单机QPS*响应时间)2/1000,2为预留一倍值,可以自行调整。
  • coreSize:估算值:(单机qps响应时间)*1.5/1000,1.5为预留0.5倍buffer,该值可以适当减少,因为线程池会有排队队列。
  • maxQueueSize:仅在allowMaximumSizeToDivergeFromCoreSize(是否开启动态线程数)为true时才生效。建议设置core的两倍大小。

七、Hystrix dashBoard界面详解

搭建步骤见 Hystrix 文章

7.1 访问dashBoard监控界面

界面访问地址
http://127.0.0.1:9007/amaster-report-server/actuator/hystrix.stream

在这里插入图片描述

通过Hystrix Dashboard主页面的文字介绍,我们可以知道,Hystrix Dashboard共支持三种不同的监控方式

  1. 默认的集群监控:通过URL:http://turbine-hostname:port/turbine.stream开启,实现对默认集群的监控。
  2. 指定的集群监控:通过URL:http://turbine-hostname:port/turbine.stream?cluster=[clusterName]开启,实现对clusterName集群的监控。
  3. 单体应用的监控:通过URL:http://hystrix-app:port/hystrix.stream开启,实现对具体某个服务实例的监控。
  4. Delay:控制服务器上轮询监控信息的延迟时间,默认为2000毫秒,可以通过配置该属性来降低客户端的网络和CPU消耗。
  5. Title:该参数可以展示合适的标题。

调用的格式页面中已给出,第一个文本框中是需要监控的服务或者集群的地址,这里暂时不需要监控集群,所以我们输入监控的服务地址即可,即输入“http://127.0.0.1:9007/amaster-report-server/hystrix”;

“Delay”文本框中是轮询调用服务监控信息的延迟时间,默认是2000ms(2s);

“Title”文本框中是监控页面的标题,这里我们输入“hystrix服务调用商品服务”,然后单击“Monitor Stream”就可以进入Hystrix Dashboard页面,如图所示。

被监控服务配置:
因为Hystrix是通过监控服务调用监控信息的,并且需要访问被监控服务的“/hystrix.stream”接口,而这个接口也是Actuator监控的一个端点,所以需要在服务调用者的pom.xml文件中添加Actuator依赖,并开放监控的端点信息。

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

在访问
Unable to connect to Command Metric Stream.
在这里插入图片描述

http://127.0.0.1:9007/amaster-report-server/actuator/hystrix.stream

访问成功后界面显示如下
在这里插入图片描述
我们把监控的时常周期调长,多刷新几次访问接口可以看到监控的访问界面的统计会发生变化

在这里插入图片描述

7.2 dashBoard 界面监控参数详解

在这里插入图片描述

在这里插入图片描述

Spring Cloud是一个基于Spring Boot的微服务框架。它提供了一系列的组件和工具,帮助开发者快速构建分布式系统,包括服务注册与发现、配置中心、断路器、服务网关、负载均衡、分布式跟踪等。下面我来详细介绍一下Spring Cloud框架的一些组件和特点。 1. 服务注册与发现 Spring Cloud提供了服务注册与发现的解决方案,包括Eureka、Consul和Zookeeper。这些组件可以让服务自动注册到服务注册中心,并且可以根据服务名称进行服务发现,实现了服务之间的解耦。 2. 配置中心 Spring Cloud Config可以集中管理应用程序的配置,将配置信息存储在Git、SVN或本地文件系统中,支持版本控制和配置历史记录,实现了应用程序配置的统一管理和动态更新。 3. 断路器 Spring Cloud提供了Hystrix组件,实现了服务的断路器模式,解决了服务之间的故障和延迟问题,提高了系统的可用性和稳定性。 4. 服务网关 Spring Cloud Gateway是一个基于Spring WebFlux的服务网关,可以实现路由、负载均衡、熔断、限流等功能,可以作为服务的入口,提供一致性和安全性的服务访问。 5. 负载均衡 Spring Cloud提供了Ribbon组件,实现了负载均衡的功能,可以根据规则和算法将请求分发到不同的服务实例上,提高了系统的并发能力和性能。 6. 分布式跟踪 Spring Cloud Sleuth可以实现分布式系统的跟踪和监控,可以记录服务之间的调用链路和请求信息,帮助开发者快速定位问题和优化系统性能。 总之,Spring Cloud框架提供了一系列的组件和工具,帮助开发者快速构建分布式系统,提高了系统的可用性、稳定性和性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值