Spring Cloud Hystrix 参数配置、简单使用、DashBoard

Spring Cloud Hystrix

文章目录

  • Spring Cloud Hystrix
    • 一、Hystrix 服务降级
    • 二、Hystrix使用示例
    • 三、OpenFeign Hystrix
    • 四、Hystrix参数
        • HystrixCommand.Setter核心参数
        • Command Properties
        • Fallback降级配置
        • Circuit Breaker 熔断器配置
        • Metrix 健康统计配置
        • Request Context 相关参数
        • Collapser Properties 命令合并配置
        • ThreadPool线程池配置
    • 五、监控Hystrix-DashBoard
      • 部署步骤:
        • 监控平台:Hystrix-DashBoard
        • 被监控服务配置:

Spring Cloud Hystrix 是一款优秀的服务容错与保护组件,也是 Spring Cloud 中最重要的组件之一。

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

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

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

一、Hystrix 服务降级

Hystrix 提供了服务降级功能,能够保证当前服务不受其他服务故障的影响,提高服务的健壮性。

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

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

Hystrix的降级策略:

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

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

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

  • 资源隔离降级

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

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

二、Hystrix使用示例

改造现有服务

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>

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

@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 "资源隔离拒绝,请稍后重试";
    }
  
}

3.全局参数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

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

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

三、OpenFeign Hystrix

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

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>

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();
}

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 "服务降级";
            }
        }
    }
}

4.定义HystrixServerFallback.class

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

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() and HystrixCollapser.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-DashBoard

1.新建Hystrix-DashBoard项目,引入pom依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
  </dependencies>

2.application.yml文件配置

server:
  port: 8082
spring:
  application:
    name: hystrix-dashboard

hystrix:
  dashboard:
     proxy-stream-allow-list: "*"

3.在启动类上添加@EnableHystrixDashboard注解开启Dashboard

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

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

4.启动服务访问地址 “http://localhost:7020/hystrix”,可以看到Hystrix Dashboard入口

在这里插入图片描述

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

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

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

被监控服务配置:

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

1.被监控服务pom文件增加依赖

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

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

2.application.yml增加配置信息

# 暴漏监控信息
management:
  endpoints:
  	web:
  	  exposure:
  	     include: "*"

在这里插入图片描述
在这里插入图片描述

  • 20
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山风wind

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值