在fallBack请求里获取Spring Cloud Gateway 的熔断异常

目的#

spring cloud gateway配置了一个超时熔断:

Copy
# hystrix 10秒后自动超时 hystrix.command.fallBackCmd.execution.isolation.thread.timeoutInMilliseconds=10000

当发生超时时,会进入到我们配置的fallbackUri请求逻辑,目前需要返回“接口请求超时信息”,而不是笼统的“服务不可用信息”,因此需要在该方法内部获取详细的异常信息

查看源码逻辑#

查看该方法org.springframework.cloud.gateway.filter.factory.HystrixGatewayFilterFactory.RouteHystrixCommand#resumeWithFallback

Copy
@Override protected Observable<Void> resumeWithFallback() { if (this.fallbackUri == null) { return super.resumeWithFallback(); } // TODO: copied from RouteToRequestUrlFilter URI uri = exchange.getRequest().getURI(); // TODO: assume always? boolean encoded = containsEncodedParts(uri); URI requestUrl = UriComponentsBuilder.fromUri(uri).host(null).port(null) .uri(this.fallbackUri).scheme(null).build(encoded).toUri(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl); addExceptionDetails(); ServerHttpRequest request = this.exchange.getRequest().mutate() .uri(requestUrl).build(); ServerWebExchange mutated = exchange.mutate().request(request).build(); // Before we continue on remove the already routed attribute since the // fallback may go back through the route handler if the fallback // is to another route in the Gateway removeAlreadyRouted(mutated); return RxReactiveStreams.toObservable(getDispatcherHandler().handle(mutated)); }

可以发现HystrixGatewayFilter在处理fallBack逻辑时,将异常信息塞到了exchange的org.springframework.cloud.gateway.support.ServerWebExchangeUtils#GATEWAY_REQUEST_URL_ATTR属性里,因此,直接在controller的方法里获取即可

简单示例#

Copy
@Log4j2 @RestController public class DefaultHystrixController { /** * 服务降级处理 * * @return ResponseVO */ @RequestMapping("/defaultFallBack") public ResponseVO<Void> defaultFallBack(ServerWebExchange exchange) { log.warn("服务降级...{}", Objects.toString(exchange.getAttribute(ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR))); Exception exception = exchange.getAttribute(ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR); if(exception instanceof HystrixTimeoutException) { return ResponseFactory.errorResponseFromMsg("网关接口请求超时..."); } return ResponseFactory.errorResponseFromMsg("服务暂时不可用,请稍后重试..."); } }
posted @   风一样的码农  阅读(1245)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示
CONTENTS