如何在spring cloud gateway中设置超时?
Posted
技术标签:
【中文标题】如何在spring cloud gateway中设置超时?【英文标题】:How to set a time out in spring cloud gateway? 【发布时间】:2020-11-27 17:50:36 【问题描述】:如何在spring cloud gateway
中设置time-out
?
routeLocatorBuilder.routes()
.route("test-api", r -> r.path("/api/**")).uri(apiLb))
.route("test-doc", r -> r.path("/doc/**")).uri(docLb));
有没有办法为ROUTE
- doc
设置一个超时时间。
【问题讨论】:
【参考方案1】:引用自spring doc
设置global time-out
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000
response-timeout: 5s
每条路由超时:-
- id: per_route_timeouts
uri: https://example.org
predicates:
- name: Path
args:
pattern: /delay/timeout
metadata:
response-timeout: 200
connect-timeout: 200
在 Java 中:
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.CONNECT_TIMEOUT_ATTR;
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.RESPONSE_TIMEOUT_ATTR;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeBuilder)
return routeBuilder.routes()
.route("test1", r ->
return r.host("*.somehost.org").and().path("/somepath")
.filters(f -> f.addRequestHeader("header1", "header-value-1"))
.uri("http://someuri")
.metadata(RESPONSE_TIMEOUT_ATTR, 200)
.metadata(CONNECT_TIMEOUT_ATTR, 200);
)
.build();
【讨论】:
对我来说它不起作用***.com/questions/64935162/…你能帮我吗?【参考方案2】:接受的答案有效如果您没有使用 R4J 断路器或时间限制器...但如果您这样做,上述设置将不足,实际上将被 R4J 设置覆盖。讨论了here 和here,在撰写本文时可以找到当前的解决方法here...基本上,您编写一个自定义 bean,以便它遵循配置设置:
@Bean
public ReactiveResilience4JCircuitBreakerFactory reactiveResilience4JCircuitBreakerFactory(final CircuitBreakerRegistry circuitBreakerRegistry, final TimeLimiterRegistry timeLimiterRegistry)
ReactiveResilience4JCircuitBreakerFactory reactiveResilience4JCircuitBreakerFactory = new ReactiveResilience4JCircuitBreakerFactory();
reactiveResilience4JCircuitBreakerFactory.configureCircuitBreakerRegistry(circuitBreakerRegistry);
reactiveResilience4JCircuitBreakerFactory.configureDefault(id ->
CircuitBreakerConfig circuitBreakerConfig = circuitBreakerRegistry.find(id).isPresent() ? circuitBreakerRegistry.find(id).get().getCircuitBreakerConfig()
: circuitBreakerRegistry.getDefaultConfig();
TimeLimiterConfig timeLimiterConfig = timeLimiterRegistry.find(id).isPresent() ? timeLimiterRegistry.find(id).get().getTimeLimiterConfig()
: timeLimiterRegistry.getDefaultConfig();
return new Resilience4JConfigBuilder(id)
.circuitBreakerConfig(circuitBreakerConfig)
.timeLimiterConfig(timeLimiterConfig)
.build();
);
return reactiveResilience4JCircuitBreakerFactory;
【讨论】:
我认为接受的答案对于香草路线是正确的。如果你插入一个断路器,你还应该检查它的超时时间 @TobiaZambon 是的,你是对的,我将编辑答案以添加说明。以上是关于如何在spring cloud gateway中设置超时?的主要内容,如果未能解决你的问题,请参考以下文章
如何配置 spring-cloud-gateway 以使用 sleuth 记录请求/响应正文