背景
当大量请求进入网关时发现有很多服务拥挤,异常的报错。检查后发现网关实现了动态路由,但是yaml中的限流配置并不对动态路由服务生效,配置如下:
hystrix:
command:
defalut:
execution:
isolation:
strategy: THREAD
thread:
timeoutInMilliseconds: 6000
fallbackcmd:
execution:
isolation:
thread:
## 超时时间
timeoutInMilliseconds: 20000
此部分配置仅对配置中指定的服务生效,并不对动态路由的服务生效。网上找了半天,没找到解决方法,于是做一下记录。
方案
SpringCloudGateway动态路由实现RouteLocator自定义路由转发器,完成容器注入的代码如下:
builder.routes()
.route(r -> r.path(URL) .filters(f ->
f.filter(new CustomRouteLocatorRequestFilter())
// 修改返回 reponse 内容返回体
.modifyResponseBody(String.class, String.class,
(exchange, s) -> {
自定义规则,此部分省略
.....
}).hystrix(config -> config.setName(CUSTOMROUTELOCATORID_HYSTRIX_NAME)
.setSetter(HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Group"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
.withExecutionIsolationThreadInterruptOnTimeout(true)
.withExecutionTimeoutInMilliseconds(6000)
.withFallbackEnabled(true)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(100)))
.setFallbackUri(CUSTOMROUTELOCATORID_HYSTRIX_PATH))
)
// baseUrl
.uri(shopexProperties.getUrl())
.order(0)
.id(CUSTOMROUTELOCATORID)
)
.build();
上述代码中,setSetter后即为设置动态路由的熔断规则,对应上述静态配置。