应该如何在 Spring WebClient 中格式化 URL 以避免最大数量的 URI 标记?

问题描述 投票:0回答:1

我们在

的日志中收到警告
Reached the maximum number of URI tags for 'http.client.requests'. Are you using 'uriVariables'

来自

org.springframework.boot.actuate.autoconfigure.metrics.OnlyOnceLoggingDenyMeterFilter
,这表明我们没有按预期格式化我们的 URI。

我们正在使用

    return webClient
        .get()
        .uri(
            builder ->
                builder
                    .path("users/{userId}/summary")
                    .queryParam("timezone", "{timezone}")
                    .build(Map.of("userId", userId, "timezone", timezone)))

那没有用(导致上述警告)。这有点令人惊讶,因为最后一个参数 is uriVariables,正如警告建议使用的那样。

然后我们试了

    String uri = UriComponentsBuilder.fromPath("users/{userId}/summary")
        .queryParam("timezone", "{timezone}")
        .toUriString();
    return webClient
        .get()
        .uri(uri, Map.of("userId", userId, "timezone", timezone)))
    }

但是 also 不起作用,因为

userId
周围的括号被编码,然后 userId 不会被 uriVariables 替换。

我们可以通过在

.build()
调用之前添加一个
.toUriString()
来解决这个问题,将构建器变成
UriComponents
并跳过编码步骤,但是这很容易出错(如果有人忘记了那一行)。此外,这仍然感觉很糟糕,因为
.uri(
调用随后又创建了一个构建器,然后再次构建。

您应该如何以干净直接的方式使用

uriVariables
,以便报告 Actuator 指标运行良好?

java spring-boot spring-boot-actuator
1个回答
0
投票

我看到了这个警告,我相信这是因为添加了查询参数

queryParam("timezone", "{timezone}")
。即使查询参数相同,也会为每个请求创建 url,并将作为
tag
添加到千分尺指标

我们遵循的替代解决方案是创建完整的 url,其中包含查询参数和路径参数的占位符,因为所有这些在开始时都是已知的,而不是动态添加的

String url = users/{userId}/summary?timezone={timezone}

然后传递

Map

中的值
return webClient
    .get()
    .uri(uri, Map.of("userId", userId, "timezone", timezone)))
© www.soinside.com 2019 - 2024. All rights reserved.