当前位置: 代码网 > it编程>编程语言>Java > SpringBoot应用对接Prometheus监控的完整指南

SpringBoot应用对接Prometheus监控的完整指南

2026年07月31日 Java 我要评论
本文档介绍如何将 spring boot 应用接入 prometheus 监控体系,分无认证和 basic auth 认证两种情况说明。一、技术栈组件用途micrometer指标采集门面spring

本文档介绍如何将 spring boot 应用接入 prometheus 监控体系,分无认证basic auth 认证两种情况说明。

一、技术栈

组件用途
micrometer指标采集门面
spring boot actuator暴露监控端点
prometheus指标采集 + 时序数据库
grafana指标可视化

二、通用步骤(两种场景都需要)

2.1 引入依赖

<!-- spring boot actuator -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-actuator</artifactid>
</dependency>
<!-- prometheus registry -->
<dependency>
    <groupid>io.micrometer</groupid>
    <artifactid>micrometer-registry-prometheus</artifactid>
</dependency>

2.2 配置 application.yml

server:
  port: 8086                                  # 业务端口
spring:
  application:
    name: janus-service1
management:
  server:
    port: 18086                                # 管理端口,与应用端口隔离
  endpoints:
    web:
      exposure:
        include: health,info,prometheus        # 暴露 prometheus 端点
  endpoint:
    prometheus:
      enabled: true                            # 启用 prometheus 端点
  metrics:
    tags:
      application: ${spring.application.name}  # 给指标打标签,便于区分

2.3 k8s deployment 配置

apiversion: apps/v1
kind: deployment
metadata:
  name: janus-service1
  namespace: gateway-default
spec:
  template:
    metadata:
      annotations:
        # ============================================================
        # 场景一:无认证(直接抓取)
        # ============================================================
        prometheus.io/scrape: "true"
        prometheus.io/kind: "janus-service1"
        prometheus.io/port: "18086"
        prometheus.io/path: "/actuator/prometheus"
        # ============================================================
        # 场景二:basic auth 认证(额外添加)
        # ============================================================
        # prometheus.io/auth: "basic"          # ← 有认证时取消注释
    spec:
      containers:
        - name: janus-service1
          image: your-registry/janus-service1:latest
          ports:
            - name: http
              containerport: 8086
              protocol: tcp
            - name: management
              containerport: 18086               # 管理端口
              protocol: tcp

三、场景一:无认证(内网/测试环境)

3.1 场景说明

  • prometheus 直接抓取 /actuator/prometheus 端点
  • 无需用户名密码验证
  • 适用于内网环境或测试环境

3.2 配置清单

配置项说明
prometheus.io/scrape"true"允许 prometheus 抓取
prometheus.io/port"18086"抓取端口
prometheus.io/path"/actuator/prometheus"抓取路径
prometheus.io/auth不配置无需认证

3.3 验证命令

# 1. pod 内验证
curl http://localhost:18086/actuator/prometheus | head -10
# 2. 集群内验证
curl http://<pod-ip>:18086/actuator/prometheus | head -10
# 3. 查看 prometheus targets
http://<prometheus-host>:9090/targets
# 预期: state = up ✅

四、场景二:basic auth 认证(生产环境)

4.1 场景说明

  • prometheus 抓取时需要携带 basic auth 凭证
  • 应用需要验证请求中的用户名密码
  • 适用于生产环境,安全性更高

4.2 新增依赖

<!-- 仅场景二需要 -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-security</artifactid>
</dependency>

4.3 配置 application.yml

spring:
  security:
    user:
      # ⚠️ 必须与 prometheus 配置中的 basic_auth 一致
      name: username
      password: axxxxxxxxxxxxxxxxxxxxxxx
management:
  # ... 与场景一相同,保持不变

4.4 配置 security(只保护 /actuator 路径)

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.core.annotation.order;
import org.springframework.security.config.customizer;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;
import org.springframework.security.web.securityfilterchain;

@configuration
@enablewebsecurity
public class managementsecurityconfig {

    /**
     * 只保护 /actuator/** 路径,使用 basic auth
     */
    @bean
    @order(1)
    public securityfilterchain managementsecurityfilterchain(httpsecurity http) throws exception {
        http.securitymatcher("/actuator/**")
            .authorizehttprequests(auth -> auth.anyrequest().authenticated())
            .httpbasic(customizer.withdefaults())
            .csrf(csrf -> csrf.disable());
        return http.build();
    }

    /**
     * 其他所有请求放行(不影响业务接口)
     */
    @bean
    @order(2)
    public securityfilterchain defaultsecurityfilterchain(httpsecurity http) throws exception {
        http.authorizehttprequests(auth -> auth.anyrequest().permitall())
            .csrf(csrf -> csrf.disable());
        return http.build();
    }
}

4.5 k8s 注解(添加 auth 标记)

annotations:
  prometheus.io/scrape: "true"
  prometheus.io/kind: "janus-service1"
  prometheus.io/port: "18086"
  prometheus.io/path: "/actuator/prometheus"
  prometheus.io/auth: "basic"   # ← 告诉 prometheus 需要认证

4.6 prometheus 配置(运维侧)

scrape_configs:
  - job_name: 'janus-service1'
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      # 只抓取 scrape=true 的 pod
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      # 只抓取 auth=basic 的 pod
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_auth]
        action: keep
        regex: basic
      # 使用自定义路径
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
        action: replace
        target_label: __metrics_path__
      # 使用自定义端口
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        action: replace
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: $1:$2
        target_label: __address__
    # basic auth 认证配置
    basic_auth:
      username: username
      password: a48xxxxxxxxxxxxxxxxxxxxxxxxxx391

到此这篇关于springboot应用对接prometheus监控的完整指南的文章就介绍到这了,更多相关springboot接入prometheus监控内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com