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