首页 > 解决方案 > 如何使用 WebClient 或 HttpClient 获取请求指标

问题描述

我正在尝试获取与单个请求相关联的指标(dns 解析器时间、tls 握手时间......)并将指标与响应相关联。

目的是执行 http 请求,处理响应并将请求的状态和指标存储在某处。

HttpClientMetricsHandlerHttpClientMetricsRecorder在全球范围内记录指标。它似乎不适用。

我已经开始研究重做(但根据请求)HttpClientMetricsHandler正在做什么并通过调用注册自定义处理程序:

HttpClient httpClient = HttpClient.create().doOnChannelInit(...)

请求的指标可以存储为通道的属性并通过执行以下操作进行检索:

httpClient.get().responseConnection((httpClientResponse, connection) -> {
   connection.channel().attr()
});

这似乎很复杂,我不知道这是否是实现目标的最佳方式。有没有更简单的?

编辑

我最终使用了Context API

HttpClient httpClient = HttpClient
        .create()
        .doOnChannelInit((connectionObserver, channel, remoteAddress) -> {
            // Get the metrics bean from the context and propagate to the metrics handler  
            Metrics metrics = connectionObserver.currentContext().get("metrics");
            channel.pipeline().addAfter(NettyPipeline.ReactiveBridge,
                    NettyPipeline.HttpMetricsHandler, new HttpClientMetricsHandler(metrics));
        });


httpClient.get()
        .response()
        .map(httpClientResponse -> {
            // Get the metrics bean tied with the response 
            Metrics metrics = httpClientResponse.currentContextView().get("metrics");
            return true;

        })
        .contextWrite(ctx -> {
            // Add the metrics bean to the context
            return ctx.put("metrics", new Metrics());
        })
        .subscribe();

我仍然不确定这不是正确的方法/最好的方法

标签: javaspring-webfluxproject-reactorspring-webclient

解决方案


推荐阅读