如何在 webclient 中跨 URI 聚合指标?

How to aggregate metrics across URIs in webclient?

我有一个 WebClient 调用后端:

https://example.com/foo?q=1 https://example.com/foo?q=2 https://example.com/foo?q=3

我想跨端点收集指标。目前,每个 uri 都是单独收集的。

有没有办法配置 MetricsWebClientFilterFunction 来实现?

我添加了自定义 WebClientExchangeTagsProvider 并将其注册为 bean:

class SameUriWebClientExchangeTagsProvider : WebClientExchangeTagsProvider {
    override fun tags(request: ClientRequest, response: ClientResponse?, throwable: Throwable?): Iterable<Tag> {
        val method = WebClientExchangeTags.method(request)
        val uri = tag(request)
        val clientName = WebClientExchangeTags.clientName(request)
        val status = WebClientExchangeTags.status(response, throwable)
        val outcome = WebClientExchangeTags.outcome(response)
        return listOf(method, uri, clientName, status, outcome)
    }

    private fun tag(request: ClientRequest): Tag {
        val uri = request.attribute(WebClient::class.java.name + ".uriTemplate")
            .orElseGet {
                request.url().toString()
            } as String

        return Tag.of("uri", URI(uri).path)
    }
}

@checketts 建议使用 uri 模板,这是 ihmo 更简单的解决方案。

所以在 WebClient 中而不是使用:

.uri { uri -> uri.path("foo").queryParam("q", "1").build() }

我用过:

 .uri("foo?q={id}", "1")

在后者下面WebClient设置属性:

attribute(URI_TEMPLATE_ATTRIBUTE, uriTemplate);

后来在WebClientExchangeTags中使用:

String uri = (String) request.attribute(URI_TEMPLATE_ATTRIBUTE).orElseGet(() -> request.url().toString());