java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot接入Prometheus监控

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

作者:流烟默

本文详细介绍了Spring Boot中应用接入Prometheus监控的两种方案,即无认证和Basic Auth认证,文中的示例代码讲解详细,帮你快速实现应用指标的可视化监控

本文档介绍如何将 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 场景说明

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 场景说明

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监控内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文