资源隔离触发降级
平台隔离,部署隔离,业务隔离,服务隔离,资源隔离
下面讲一个资源隔离:
- 线程池隔离 参考Hystrix线程隔离技术解析-线程池
- 信号量隔离 参考Hystrix线程隔离技术解析-信号量
其他参考:基于Hystrix信号量资源隔离与限流
优化user-service-provider原有的配置信息application.yml:
# 调用的时候ribbon本身也有超时时间,和hystrix一起就是有两个超时时间了
hystrix:
command:
default: #全局配置, feignclient#method(param)
execution:
timeout:
enable: true
isolation:
thread:
timeoutInMilliseconds: 3000
OrderServiceFeignClient#orders:
execition:
isolation:
strategy: SEMAPHORE #配置线程的策略
semaphore:
maxConcurrentRequests: 10 #最大请求数10,同时最多处理10个请求
OrderServiceFeignClient#insert:
execition:
isolation:
strategy: THREAD
threadpool:
order-service: # 针对order-servive去配置线程池资源的信息
coreSize: 2
maxQueueSize: 100
queueSizeRejectionThreshold: 80 #队列大小超过80的时候开始拒绝
关于熔断降级的hystrix提供了一个dashboard可以直接查看,现在创建spring-cloud-hystrix-dashboard项目
配置端口:9092,启动成功后,访问:http://localhost:9092/hystrix
management.endpoints.web.exposure.include 增加hystrix.stream
management:
endpoints:
web:
exposure:
include: refresh,hystrix.stream
user-service-provider启动,访问:http://localhost:8081/actuator/hystrix.stream
这个请求会不断地发出ping,然后把链接放在hystrixDashboard面板中进行采集数据进而展示。
写一个测试类,直接让它熔断,熔断的时候,Circuit是Open打开的状态
@GetMapping("/hystrix/test")
public String test(){
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(20);
int n = 0;
while (n<10000){
n ++ ;
try {
Thread.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
fixedThreadPool.execute(new Runnable() {
public void run() {
System.out.println("线程:"+Thread.currentThread().getName() + "在执行呢!");
//orderServiceFeignClient.orders(); 信号量隔离,其实不用设置服务提供方orders()接口中Thread.sleep()
//但在测试线程池隔离的时候,为了展示效果,把order-service-provider中的insert方法中增加Thread.sleep(),那么
//此线程在执行的过程中里面的queue可以快速达到80,触发后续请求的降级处理.
orderServiceFeignClient.insert(new OrderDto());
}
});
}
return "";
}
线程池隔离和信号量隔离还有一种注解的方式如下:
/**
* 信号量隔离实现
* 不会使用Hystrix管理的线程池处理请求。使用容器(Tomcat)的线程处理请求逻辑。
* 不涉及线程切换,资源调度,上下文的转换等,相对效率高。
* 信号量隔离也会启动熔断机制。如果请求并发数超标,则触发熔断,返回fallback数据。
* commandProperties - 命令配置,HystrixPropertiesManager中的常量或字符串来配置。
* execution.isolation.strategy - 隔离的种类,可选值只有THREAD(线程池隔离)和
SEMAPHORE(信号量隔离)。
* 默认是THREAD线程池隔离。
* 设置信号量隔离后,线程池相关配置失效。
* execution.isolation.semaphore.maxConcurrentRequests - 信号量最大并发数。默认
值是10。常见配置500~1000。
* 如果并发请求超过配置,其他请求进入fallback逻辑。 */
@HystrixCommand(fallbackMethod="semaphoreQuarantineFallback",
commandProperties={
@HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_STRATEGY,
value="SEMAPHORE"), // 信号量隔离
@HystrixProperty(name=HystrixPropertiesManager.EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS,
value="100") // 信号量最大并发数
线程池隔离
@HystrixCommand(groupKey = "order-service",
commandKey = "queryOrder",
threadPoolKey = "order-service",
threadPoolProperties = {
@HystrixProperty(name = "coreSize",value = "30"), //线程池大小
@HystrixProperty(name = "maxQueueSize",value = "100"), //最大队列长度
@HystrixProperty(name = "keepAliveTimeMinutes",value = "2"), //线程存活时间
@HystrixProperty(name = "queueSizeRejectionThreshold",value = "15") //拒绝请求
},fallbackMethod = "fallBack")