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

Spring Boot应用配置Micrometer对接带Basic Auth的Prometheus Pushgateway

为Spring Boot + Micrometer + Prometheus Pushgateway配置Basic Auth认证

针对CI环境中开启Basic Auth的Prometheus Pushgateway,有两种常用的配置方式:

方式1:通过配置文件直接配置(推荐)

直接在application.properties或application.yml中添加认证凭据,Spring Boot的Micrometer自动配置会自动将其注入到Pushgateway请求中:

application.properties示例

# 原有Pushgateway基础配置
management.metrics.export.prometheus.pushgateway.base-url=http://ci-pushgateway:9091
management.metrics.export.prometheus.pushgateway.enabled=true
management.metrics.export.prometheus.pushgateway.job=your-app-job

# 添加Basic Auth认证配置
management.metrics.export.prometheus.pushgateway.username=your-ci-username
management.metrics.export.prometheus.pushgateway.password=your-ci-password

application.yml示例

management:
  metrics:
    export:
      prometheus:
        pushgateway:
          base-url: http://ci-pushgateway:9091
          enabled: true
          job: your-app-job
          username: your-ci-username
          password: your-ci-password

方式2:自定义PushGateway Bean(复杂场景)

如果需要动态获取凭据、自定义请求逻辑等更灵活的场景,可以通过自定义Bean替换默认的PushGateway实例:

import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.web.client.RestTemplate;

@Configuration
public class PushGatewayAuthConfig {

    @Value("${management.metrics.export.prometheus.pushgateway.base-url}")
    private String pushgatewayUrl;

    @Value("${management.metrics.export.prometheus.pushgateway.username}")
    private String authUsername;

    @Value("${management.metrics.export.prometheus.pushgateway.password}")
    private String authPassword;

    @Bean
    public PushGateway pushGateway() {
        RestTemplate restTemplate = new RestTemplate();
        // 添加Basic Auth拦截器
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(authUsername, authPassword));
        return new PushGateway(pushgatewayUrl, restTemplate);
    }

    // 绑定自定义PushGateway到Prometheus指标注册表
    @Bean
    public PrometheusMeterRegistry prometheusMeterRegistry(PushGateway pushGateway) {
        PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
        registry.config().pushGateway(pushGateway);
        return registry;
    }
}

验证配置

可以开启Spring Boot的DEBUG日志,查看Pushgateway请求日志,确认请求头中包含Authorization: Basic xxxxx字段;或直接在CI环境启动应用,检查指标是否能正常推送到Pushgateway。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:24:31