需求:由于文件上传不仅要限时大小,还要单独的设置接口最大的超时时间,于是想到了改网关的Hystrix,Ribbon,超时时间,一开始设想的是通过网关来控制文件上传接口的请求超时时间为120S,而同服务内的其他接口超时时间还是原来的10秒。
后来,在测试中发现:目前项目(Edgware.RELEASE版本)配置的Hystrix超时时间配置不起作用,不管怎么设置,Hystrix都被设置成2秒超时了,我设置的代码如下:
hystrix:
command:
default: # 默认用default,控制所有走网关的服务。如果你想为某个特定的service配熔断超时策略,配置方式如下:hystrix.command.<serviceName>.execution.isolation.thread.timeoutInMilliseconds=60000
execution:
timeout:
enabled: true # 默认是开启的
isolation:
thread:
timeoutInMilliseconds: 12000 # 断路器的超时时间(默认1000毫秒),下级服务返回超出熔断器时间,即便成功,消费端消息也是TIMEOUT,所以一般断路器的超时时间需要大于ribbon的超时时间。如果hystrixTimeout小于ribbonTimeout,可能在Ribbon切换实例进行重试的过程中就会触发熔断。
# 对某服务设置单独的超时时间
ulegal-system:
execution:
isolation:
thread:
timeoutInMilliseconds: 125000 # 125s
不管是对'default'的配置还是对某服务'ulegal-system'的配置,均不起作用。
一开始是怀疑spring-cloud-starter-netflix-hystrix依赖没有引入,重新检查了一遍Hystrix的依赖,确定是有引入的。百思不得其解
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>Edgware.RELEASE</version>
</dependency>
后来Debug了,才发现配置在实例化默认值确实是1,但是设置值是2,排除是自己设置因素,就剩下版本问题了。
升级版本后解决:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>Edgware.SR6</version>
</dependency>
================================分界线===============================
为什么低版本的Hystrix配置不生效,分析底层源码:
入口:AbstractRibbonCommand 类 的 getSetter()方法是获取ribbon和hystix的超时时间的。
withExecutionTimeoutInMilliseconds(RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT + RibbonClientConfiguration.DEFAULT_READ_TIMEOUT);
此处Hystrix被写死获取了ribbon 的默认值1+1=2,所以被设置了是2秒。
protected static Setter getSetter(final String commandKey,
ZuulProperties zuulProperties) {
// @formatter:off
Setter commandSetter = Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RibbonCommand"))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
final HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(zuulProperties.getRibbonIsolationStrategy()).withExecutionTimeoutInMilliseconds(
RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT + RibbonClientConfiguration.DEFAULT_READ_TIMEOUT);
if (zuulProperties.getRibbonIsolationStrategy() == ExecutionIsolationStrategy.SEMAPHORE){
final String name = ZuulConstants.ZUUL_EUREKA + commandKey + ".semaphore.maxSemaphores";
// we want to default to semaphore-isolation since this wraps
// 2 others commands that are already thread isolated
final DynamicIntProperty value = DynamicPropertyFactory.getInstance()
.getIntProperty(name, zuulProperties.getSemaphore().getMaxSemaphores());
setter.withExecutionIsolationSemaphoreMaxConcurrentRequests(value.get());
} else if (zuulProperties.getThreadPool().isUseSeparateThreadPools()) {
final String threadPoolKey = zuulProperties.getThreadPool().getThreadPoolKeyPrefix() + commandKey;
commandSetter.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(threadPoolKey));
}
return commandSetter.andCommandPropertiesDefaults(setter);
// @formatter:on
}