You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot项目http_client_requests_指标缺失问题求解

SpringBoot中RestTemplate的Prometheus http_client_requests指标缺失解决方案

环境信息

SpringBoot版本

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.12-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

依赖配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

问题现象

使用RestTemplate发起外部请求后,访问Prometheus端点(默认路径/actuator/prometheus)时,无法找到http_client_requests相关监控指标。


解决方案

1. 正确配置RestTemplate的指标拦截器

SpringBoot不会自动为手动new出来的RestTemplate实例添加Micrometer监控拦截器,需要通过配置类让Spring为RestTemplate注入监控能力:

import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateCustomizer restTemplateCustomizer) {
        RestTemplate restTemplate = new RestTemplate();
        // 注入Micrometer监控拦截器
        restTemplateCustomizer.customize(restTemplate);
        return restTemplate;
    }
}

或者直接依赖SpringBoot的自动配置,通过@Autowired注入RestTemplate,而非手动实例化:

@Autowired
private RestTemplate restTemplate;

2. 确认Actuator端点与Metrics配置

在配置文件中确保Prometheus端点暴露、指标导出开启:

application.yml配置

management:
  endpoints:
    web:
      exposure:
        include: prometheus  # 暴露Prometheus端点
  metrics:
    export:
      prometheus:
        enabled: true  # 开启Prometheus指标导出
    tags:
      application: ${spring.application.name}  # 可选:添加应用标识标签,方便多实例区分

application.properties配置

management.endpoints.web.exposure.include=prometheus
management.metrics.export.prometheus.enabled=true
management.metrics.tags.application=${spring.application.name}

3. 验证请求使用的RestTemplate实例

确保业务代码中发起外部请求的是上述配置的RestTemplate,而非未被监控拦截器处理的手动new RestTemplate()实例。如果存在多个RestTemplate实例,需要为每个需要监控的实例都注入拦截器。

4. 验证指标生成

启动项目后,手动发起几次外部请求,然后访问/actuator/prometheus,搜索http_client_requests,应该能看到类似如下的指标数据:

http_client_requests_seconds_count{application="your-app-name",client_name="example.com",method="GET",status="200",uri="/api/test",} 2.0

内容的提问来源于stack exchange,提问作者SEEDEV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:15:52