Spring Boot Actuator指标排除路径参数的实现方法问询
哈哈,这个坑我刚踩过不久!Spring Boot Actuator 默认会把路径里的每个不同参数值都当成独立的维度来统计指标,几十万不同的ID确实会把指标库搞的臃肿不堪,甚至拖慢系统。给你几个实用的解决办法,按需选就行:
方法一:全局统一聚合(推荐)
这种方式能让所有带路径参数的端点都自动聚合到对应的模板路径下(比如把/users/123、/users/456都归到/users/{id}这个指标维度),一劳永逸。
你只需要自定义一个WebMvcTagsProvider,替换掉默认的标签生成逻辑:
import io.micrometer.core.instrument.Tag; import io.micrometer.spring.web.servlet.WebMvcTags; import io.micrometer.spring.web.servlet.WebMvcTagsProvider; import org.springframework.web.servlet.HandlerMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CustomWebMvcTagsProvider implements WebMvcTagsProvider { @Override public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception) { return WebMvcTags.zip( WebMvcTags.method(request), getPathTag(request), WebMvcTags.status(response), WebMvcTags.exception(exception) ); } private Tag getPathTag(HttpServletRequest request) { // 从请求属性中获取Spring MVC解析后的路径模板 String pathTemplate = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); if (pathTemplate != null) { return Tag.of("uri", pathTemplate); } // 如果获取失败, fallback到默认的路径标签逻辑 return WebMvcTags.path(request); } }
然后在配置类里注册这个Bean:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MetricsConfig { @Bean public WebMvcTagsProvider customWebMvcTagsProvider() { return new CustomWebMvcTagsProvider(); } }
重启应用后,所有带路径参数的请求都会被聚合到对应的模板路径指标下,再也不会出现几十万条零散的计数器了。
方法二:局部端点手动指定指标
如果你只想针对某几个特定端点做聚合,可以用@Timed注解手动指定统一的指标名称,绕过默认的路径维度拆分:
import io.micrometer.core.annotation.Timed; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { // 所有调用这个接口的请求,都会统计到"user.retrieve"这个指标下 @Timed(value = "user.retrieve", description = "统计获取单个用户的请求次数") @GetMapping("/users/{id}") public User getUser(@PathVariable String id) { // 你的业务逻辑代码 } }
这种方式灵活度高,适合只需要调整少数端点的场景。
方法三:配置文件快速调整(Spring Boot 2.4+)
如果你的Spring Boot版本是2.4及以上,可以直接通过配置文件来指定忽略路径参数的匹配规则,不用写代码:
management: metrics: web: server: request: tagging: # 用Ant风格路径匹配你要聚合的端点,*匹配任意字符 ignore-patterns: "/users/*" # 或者用更精确的模板匹配,比如匹配所有带id参数的路径 # uri-template: "/users/{id}"
不过这个配置的灵活性不如前两种,适合简单场景快速验证。
内容的提问来源于stack exchange,提问作者Alejandro Agapito Bautista
相关产品推荐
相关产品推荐

