企业网站的建设公司价格,上海网站制作案例,学做网站需要什么条件,网站关键字分析Sping Cloud Hystrix 文章目录 Sping Cloud Hystrix一、Hystrix 服务降级二、Hystrix使用示例三、OpenFeign Hystrix四、Hystrix参数HystrixCommand.Setter核心参数Command PropertiesFallback降级配置Circuit Breaker 熔断器配置Metrix 健康统计配置Request Context 相关参数C…Sping Cloud Hystrix 文章目录 Sping Cloud Hystrix一、Hystrix 服务降级二、Hystrix使用示例三、OpenFeign Hystrix四、Hystrix参数HystrixCommand.Setter核心参数Command PropertiesFallback降级配置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
dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-hystrix/artifactIdversion2.0.2.RELEASE/version
/dependency2.在controller中需要增加熔断功能的接口添加注解HystrixCommand 详细参数见 Hystrix参数
RestController
RequestMapping(hystrix)
public class HystrixController {Autowiredprivate HystrixService hystrixService;// 熔断降级GetMapping({num})HystrixCommand(fallbackMethodcircuitBreakerFallback, commandProperties {HystrixProperty(nameHystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value true),// 是否开启熔断器HystrixProperty(nameHystrixPropertiesManager.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方法的参数多加个Throwablepublic String circuitBreakerFallback(Integer num, String name) {return 请求失败请稍后重试;}// 超时降级GetMappingHystrixCommand(fallbackMethod timeoutFallback, commandProperties {HystrixProperty(name HystrixPropertiesManager.EXECUTION_TIMEOUT_ENABLED, value true),// 是否开启超时降级HystrixProperty(name HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value 10000),// 请求的超时时间默认10000HystrixProperty(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: truerequestVolumeThreshold: 20errorThresholdPercentage: 50sleepWindowInMilliseconds: 5000execution:timeout:enabled: trueisolation:thread:timeoutInMilliseconds: 2000interruptOnTimeout: truesemaphore:maxConcurrentRequests: 10strategy: THREADmetrics:rollingStats:timeInMilliseconds: 10000threadpool:default:coreSize: 10maximumSize: 19allowMaximumSizeToDivergeFromCoreSize: falsekeepAliveTimeMinutes: 1maxQueueSize: -1queueSizeRejectionThreshold: 54.在启动类添加注解 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.引入依赖
dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-openfeign/artifactIdversion2.0.2.RELEASE/version
/dependency
dependencygroupIdio.github.openfeign/groupIdartifactIdfeign-httpclinet/artifactIdversion9.7.0/version
/dependency
dependencygroupIdio.github.openfeign/groupIdartifactIdfeign-hystrix/artifactIdversion9.7.0/version
/dependency2.定义Feign调用接口其中fallbackFactory中为试下的fallback方法
// fallbackFactory 实现
FeignClient(value hystrixProject, urlhttp://localhost:8085, fallbackFactory HystrixServerFallbackFactory.class)
public interface HystrixServer {GetMapping(/test)String test();
}// fallback 实现
FeignClient(value hystrixProject, urlhttp://localhost:8085, fallback HystrixServerFallback.class)
public interface HystrixServer {GetMapping(/test)String test();
}3.定义HystrixServerFallbackFactory.class
import feign.hystrix.FallbackFactory;Component
public class HystrixServerFallbackFactory implements FallbackFactoryHystrixServer {Overridepublic HystrixServer create(Throwable throwable) {return new HystrixServer() {Overridepublic 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,可选ThreadSemaphore。thread用于线程池的隔离一般适用于同步请求。semaphore是信号量模式适用于异步请求hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 命令执行超时时间默认1000mshystrix.command.default.execution.timeout.enabled 执行是否启用超时默认启用truehystrix.command.default.execution.isolation.thread.interruptOnTimeout 发生超时是是否中断默认truehystrix.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包含successfailuretimeoutrejection的次数的统计信息。默认10000.hystrix.command.default.metrics.rollingStats.numBuckets 设置一个rolling window被划分的数量若numBuckets10rolling window10000那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets 0。默认10.hystrix.command.default.metrics.rollingPercentile.enabled 执行时是否enable指标的计算和跟踪默认truehystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 设置rolling percentile window的时间默认60000hystrix.command.default.metrics.rollingPercentile.numBuckets 设置rolling percentile window的numberBuckets。逻辑同上。默认6hystrix.command.default.metrics.rollingPercentile.bucketSize 如果bucket size100window10s若这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_VALUEhystrix.collapser.default.timerDelayInMilliseconds 触发批处理的延迟也可以为创建批处理的时间该值默认10hystrix.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/10002为预留一倍值可以自行调整。 coreSize估算值单机qps响应时间*1.5/10001.5为预留0.5倍buffer该值可以适当减少因为线程池会有排队队列。 maxQueueSize仅在allowMaximumSizeToDivergeFromCoreSize是否开启动态线程数为true时才生效。建议设置core的两倍大小。
五、监控Hystrix-DashBoard
部署步骤
监控平台Hystrix-DashBoard
1.新建Hystrix-DashBoard项目引入pom依赖
dependenciesdependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-hystrix/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-hystrix-dashboard/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-actuator/artifactId/dependency/dependencies2.application.yml文件配置
server:port: 8082
spring:application:name: hystrix-dashboardhystrix: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”文本框中是轮询调用服务监控信息的延迟时间默认是2000ms2s
“Title”文本框中是监控页面的标题这里我们输入“hystrix服务调用商品服务”然后单击“Monitor Stream”就可以进入Hystrix Dashboard页面如图所示。
被监控服务配置
因为Hystrix是通过监控服务调用监控信息的并且需要访问被监控服务的“/hystrix.stream”接口而这个接口也是Actuator监控的一个端点所以需要在服务调用者的pom.xml文件中添加Actuator依赖并开放监控的端点信息。
1.被监控服务pom文件增加依赖
dependenciesdependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-hystrix/artifactIdversionRELEASE/version/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-actuator/artifactId/dependency
/dependencies2.application.yml增加配置信息
# 暴漏监控信息
management:endpoints:web:exposure:include: *