在Spring Cloud微服务架构中,大部分公司都是利用Open Feign进行服务间的调用,而比较简单的业务使用默认配置是不会有多大问题的,但是如果是业务比较复杂,服务要进行比较繁杂的业务计算,那后台很有可能会出现Read Timeout这个异常,因此定制化配置超时时间就有必要了。
一,超时时间设置有三种方法 ,以yml 文件为例:
# feign 设置超时时间
feign:
client:
config:
default:
connectTimeout: 200
readTimeout: 200
# 开启断路器(熔断器)
hystrix:
enabled: true
# 设置熔断器时间
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000
#设置ribbon 时间
ribbon:
ConnectTimeout: 200
ReadTimeout: 200
以上三种如果都设置的情况下,超时时间的最终采用的配置优先级是这样的 feign > ribbon , 他们与hystrix 并行的,如果hystrix时间短那么会先熔断,如果这两个配置时间小于hystrix,则先超时处理, 如果是升级到基于springboot 2.x 以后版本的openfeign 建议用feign 配置,如下图FeignLoadBalancer 类的执行方法
。
@Override
public RibbonResponse execute(RibbonRequest request, IClientConfig configOverride)
throws IOException {
Request.Options options;
//如果配置了feign配置了参数 则用feign的配置
if (configOverride != null) {
RibbonProperties override = RibbonProperties.from(configOverride);
options = new Request.Options(
override.connectTimeout(this.connectTimeout),
override.readTimeout(this.readTimeout));
}
//否则用ribbon的配置参数
else {
options = new Request.Options(this.connectTimeout, this.readTimeout);
}
Response response = request.client().execute(request.toRequest(), options);
return new RibbonResponse(request.getUri(), response);
}