在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("服務暫時不可用,請稍后重試...");
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM