本文介紹了Java Spring Webflow,記錄出站http調(diào)用所用的時間的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
請回答有關(guān)如何記錄http請求所用時間的小問題。
為了避免混淆,這個問題是關(guān)于日志(不是指標(biāo))的,這個問題是關(guān)于Webflow的,這個問題是關(guān)于出站呼叫的,我是客戶端,正在嘗試呼叫服務(wù)器,我需要對此操作計時,但從日志的角度來看。
基于我正在使用的這段代碼:
@Override
public Mono<String> sendOutboundRequest() {
return webClient.post().retrieve().bodyToMono(String.class);
}
到目前為止,我嘗試了.log()
,但這并不是直接寫入花費的時間,此解決方案需要從On SUBSCRIBE和ON COMPLETE OF log4j時間再解析一層時間戳。
我也嘗試了.metrics()
,這獲得了時間,但這只生成指標(biāo),而不是日志。
我還嘗試了一些環(huán)繞方法的執(zhí)行
long start = System.nanoTime();
Mono<String> result = webClientIdms.post().retrieve().bodyToMono(String.class);
long end = System.nanoTime() - start;
LOGGER.info("this will not print the actual http request time " + end);
return result;
但這不起作用,因為在反應(yīng)式堆棧中,當(dāng)執(zhí)行反應(yīng)式管道時,這不會對請求的執(zhí)行計時。
請問記錄所用時間的正確方式是什么?
謝謝
推薦答案
如果您希望以可重用的方式完成此操作,則可以使用ExchangeFilterFunction
。您可以在spring reference docs
上找到ExchangeFilterFunction
的更多示例
下面是ExchangeFilterFunction
的一個示例實現(xiàn),它將對WebClient
進行的每個外部API調(diào)用進行計時并記錄結(jié)果。靈感來自MetricsWebClientFilterFunction
@Component
public class MetricsLoggingExchangeFilterFunction implements ExchangeFilterFunction {
private static final Logger LOGGER = LoggerFactory.getLogger(MetricsLoggingExchangeFilterFunction.class);
private static final String METRICS_WEBCLIENT_START_TIME = MetricsLoggingExchangeFilterFunction.class.getName() + ".START_TIME";
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request).doOnEach((signal) -> {
if (!signal.isOnComplete()) {
Long startTime = signal.getContextView().get(METRICS_WEBCLIENT_START_TIME);
long duration = System.currentTimeMillis() - startTime;
LOGGER.info("Downstream called taken {}ms", duration);
}
}).contextWrite(ctx -> ctx.put(METRICS_WEBCLIENT_START_TIME, System.currentTimeMillis()));
}
}
然后可以使用提供的WebClient.Builder
ie將其添加到要記錄持續(xù)時間的任何WebClient
實例中。
WebClient.builder().filter(metricsLoggingExchangeFilterFunction).build()
這篇關(guān)于Java Spring Webflow,記錄出站http調(diào)用所用的時間的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,