天天看點

在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      轉載請注明出處,謝謝~