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

目的

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

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

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

查看源码逻辑

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

                @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的方法里获取即可

简单示例

@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("服务暂时不可用,请稍后重试...");
    }
}

@Author      风一样的码农
@HomePageUrl http://www.cnblogs.com/chenpi/
@Copyright      转载请注明出处,谢谢~
posted @ 2020-12-14 15:30  风一样的码农  阅读(567)  评论(0编辑  收藏  举报