重学SpringBoot3-集成Spring Boot Actuator

news2024/10/25 15:26:16

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞👍收藏⭐评论✍

重学SpringBoot3-集成Spring Boot Actuator

  • 1. 什么是 Spring Boot Actuator?
  • 2. Spring Boot Actuator 的核心功能
  • 3. Spring Boot 3 中集成 Actuator
    • 3.1 添加依赖
    • 3.2 开启 Actuator 端点
    • 3.3 常用的 Actuator 端点
    • 3.4 健康检查 (Health Check)
    • 3.5 监控指标 (Metrics)
    • 3.6 应用信息 (Info)
    • 3.7 日志管理 (Loggers)
  • 4. 安全配置
  • 5. 总结

Spring Boot Actuator 是 Spring Boot 提供的一组内置功能,用于监控和管理应用程序。通过 Actuator,开发者可以轻松获取应用的运行时状态,执行健康检查,监控性能指标,甚至自定义端点来满足特定需求。本文将详细介绍如何在 Spring Boot 3 中整合 Spring Boot Actuator,并展示如何配置和使用 Actuator 提供的核心功能。

1. 什么是 Spring Boot Actuator?

Spring Boot Actuator 是一组能够帮助我们监控和管理 Spring Boot 应用的工具。它提供了很多有用的端点,用来查看应用的各种信息,如健康状况、Bean 信息、应用配置、日志级别等。Actuator 默认提供了一些内置的端点,但我们也可以根据需求自定义新的端点。

2. Spring Boot Actuator 的核心功能

Spring Boot Actuator 的核心功能主要包括:

  • 健康检查 (Health Check):检测应用及其依赖服务(如数据库、消息队列等)的健康状况。
  • 监控指标 (Metrics):收集和展示应用程序的运行指标,如内存使用、线程状态、GC 情况等。
  • 应用程序信息 (Info):展示应用程序的基本信息,如版本、环境变量等。
  • 审计 (Auditing):记录应用的安全事件。
  • HTTP 跟踪 (HTTP Tracing):跟踪 HTTP 请求和响应。
  • 日志级别管理 (Loggers):动态调整日志级别。

3. Spring Boot 3 中集成 Actuator

3.1 添加依赖

创建模块

在 Spring Boot 3 项目中使用 Actuator,首先需要在 pom.xml 文件中添加相关依赖:

		<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>

在引入 spring-boot-starter-actuator 依赖后,Spring Boot 会自动配置 Actuator 并启用其默认端点。

3.2 开启 Actuator 端点

默认情况下,Spring Boot Actuator 只开启少量的端点。我们可以通过 application.propertiesapplication.yml 配置文件来自定义启用哪些端点。

application.yml 中,可以通过以下配置开启所有的 Actuator 端点:

management:
  endpoints:
    web:
      exposure:
        include: '*'

此配置会启用所有的 Actuator 端点。若仅希望启用部分端点,可以将 '*' 替换为具体的端点名,如:

management:
  endpoints:
    web:
      exposure:
        include: health,info

3.3 常用的 Actuator 端点

一些常用的 Actuator 端点包括:

  • /actuator/health:显示应用程序的健康状况。
  • /actuator/info:显示应用程序的基本信息。
  • /actuator/metrics:展示应用的监控指标。
  • /actuator/loggers:查看和修改应用程序的日志级别。
  • /actuator/env:显示应用程序的环境属性和配置信息。

可以通过浏览器或 HTTP 客户端访问 http://localhost:8080/actuator 展示出所有可以用的监控端点。

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/actuator",
            "templated": false
        },
        "beans": {
            "href": "http://localhost:8080/actuator/beans",
            "templated": false
        },
        "caches-cache": {
            "href": "http://localhost:8080/actuator/caches/{cache}",
            "templated": true
        },
        "caches": {
            "href": "http://localhost:8080/actuator/caches",
            "templated": false
        },
        "health": {
            "href": "http://localhost:8080/actuator/health",
            "templated": false
        },
        "health-path": {
            "href": "http://localhost:8080/actuator/health/{*path}",
            "templated": true
        },
        "info": {
            "href": "http://localhost:8080/actuator/info",
            "templated": false
        },
        "conditions": {
            "href": "http://localhost:8080/actuator/conditions",
            "templated": false
        },
        "configprops": {
            "href": "http://localhost:8080/actuator/configprops",
            "templated": false
        },
        "configprops-prefix": {
            "href": "http://localhost:8080/actuator/configprops/{prefix}",
            "templated": true
        },
        "env": {
            "href": "http://localhost:8080/actuator/env",
            "templated": false
        },
        "env-toMatch": {
            "href": "http://localhost:8080/actuator/env/{toMatch}",
            "templated": true
        },
        "loggers": {
            "href": "http://localhost:8080/actuator/loggers",
            "templated": false
        },
        "loggers-name": {
            "href": "http://localhost:8080/actuator/loggers/{name}",
            "templated": true
        },
        "heapdump": {
            "href": "http://localhost:8080/actuator/heapdump",
            "templated": false
        },
        "threaddump": {
            "href": "http://localhost:8080/actuator/threaddump",
            "templated": false
        },
        "metrics-requiredMetricName": {
            "href": "http://localhost:8080/actuator/metrics/{requiredMetricName}",
            "templated": true
        },
        "metrics": {
            "href": "http://localhost:8080/actuator/metrics",
            "templated": false
        },
        "scheduledtasks": {
            "href": "http://localhost:8080/actuator/scheduledtasks",
            "templated": false
        },
        "mappings": {
            "href": "http://localhost:8080/actuator/mappings",
            "templated": false
        }
    }
}

例如,访问 http://localhost:8080/actuator/health 会返回应用程序的健康信息。

/actuator/health

3.4 健康检查 (Health Check)

/actuator/health 端点用于检查应用程序及其依赖服务的健康状况。Spring Boot Actuator 内置了一些常见服务的健康指示器,如数据库、消息队列等。

可以在 application.yml 中配置健康检查的详情:

management:
  endpoint:
    health:
      show-details: always

这将确保 /actuator/health 端点返回详细的健康检查信息。

 show-details: always

若需要自定义健康指示器,可以实现 HealthIndicator 接口:

package com.coderjia.boot3actuator.config;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

/**
 * @author CoderJia
 * @create 2024/10/13 上午 10:33
 * @Description
 **/
@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // 自定义健康检查逻辑
        boolean serviceRunning = checkExternalService();
        if (serviceRunning) {
            return Health.up().withDetail("service", "running").build();
        } else {
            return Health.down().withDetail("service", "stopped").build();
        }
    }

    private boolean checkExternalService() {
        // 模拟外部服务的检查
        return true;
    }
}

访问 /actuator/health 时将会包含自定义健康检查的结果。

自定义健康检查

3.5 监控指标 (Metrics)

/actuator/metrics 端点可以显示应用程序的运行时指标,包括 JVM 内存使用情况、CPU 使用率、垃圾回收次数、线程信息等。

/actuator/metrics 端点

访问 /actuator/metrics 时,可以获取所有可用的监控指标。例如,要查看 JVM 内存使用情况,可以访问 /actuator/metrics/jvm.memory.used

查看 JVM 内存使用

Actuator 使用 Micrometer 来收集和导出这些指标,Micrometer 支持多种监控系统,如 Prometheus、Graphite 等。如果你需要将指标导出到外部监控系统,可以在 application.yml 中进行配置:

management:
  metrics:
    export:
      prometheus:
        enabled: true

3.6 应用信息 (Info)

/actuator/info 端点可以显示应用程序的基本信息,如版本号、构建时间等。这些信息可以通过 application.yml 文件进行配置:

management:
  endpoints:
    web:
      exposure:
        include: '*'
  info:
    env:
      enabled: true
info:
  app:
    name: My Spring Boot App
    version: 1.0.0
    description: This is a demo application

访问 /actuator/info 时将返回这些配置的信息。

/actuator/info 端点

3.7 日志管理 (Loggers)

/actuator/loggers 端点允许我们查看和动态调整应用程序的日志级别。访问 /actuator/loggers 将显示应用程序中所有的日志记录器及其当前日志级别。

/actuator/loggers 端点

可以通过发送 HTTP POST 请求来动态更改日志级别:

curl -X POST -d '{"configuredLevel": "DEBUG"}' http://localhost:8080/actuator/loggers/com.coderjia.boot3actuator.controller

此请求将 com.coderjia.boot3actuator.controller 这个包的日志级别设置为 DEBUG

image-20241013105721700

4. 安全配置

默认情况下,Actuator 端点只在本地开发时可用,生产环境通常需要添加安全机制。可以通过 Spring Security 为 Actuator 端点添加认证和授权。

首先,在 pom.xml 中添加 Spring Security 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

接着,在 application.yml 中配置安全设置:

spring:
  # 配置登录springboot admin管理端的账号密码
  security:
    user:
      name: admin
      password: 123456
      roles: ADMIN
management:
  endpoints:
    web:
      exposure:
        include: '*'  # 指定哪些端点公开
  security:
    enabled: true  # 启用安全性

然后,在 SecurityConfig 中配置基本认证:

package com.coderjia.boot3actuator.config;

import org.springframework.context.annotation.Bean;
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;

/**
 * @author CoderJia
 * @create 2024/10/13 上午 10:59
 * @Description
 **/
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/actuator/**").hasRole("ADMIN") // 保护所有 Actuator 端点,只允许 ADMIN 角色访问
                        .anyRequest().permitAll() // 其他请求允许访问
                )
                .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

这样,访问 Actuator 端点时将需要提供用户名和密码,使用配置的 admin 和123456 登录即可。

登录

5. 总结

通过 Spring Boot 3 中的 Actuator,我们可以非常方便地监控和管理应用程序的运行时状态。Actuator 提供了丰富的内置端点,帮助我们查看应用的健康状态、运行时指标、日志级别等。同时,Actuator 还允许我们根据需求自定义健康检查和监控端点。结合 Spring Security,我们可以轻松地为 Actuator 端点添加认证和授权,保证生产环境的安全性。

Actuator 是开发人员和运维人员监控 Spring Boot 应用的得力工具,尤其是在复杂的生产环境中,Actuator 能帮助我们快速发现问题并及时处理。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2210746.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ElasticSearch是什么?

1.概述 Elasticsearch 是一个基于 Apache Lucene 构建的开源分布式搜索引擎和分析引擎。它专为云计算环境设计&#xff0c;提供了一个分布式的、高可用的实时分析和搜索平台。Elasticsearch 可以处理大量数据&#xff0c;并且具备横向扩展能力&#xff0c;能够通过增加更多的硬…

2014年国赛高教杯数学建模C题生猪养殖场的经营管理解题全过程文档及程序

2014年国赛高教杯数学建模 C题 生猪养殖场的经营管理 某养猪场最多能养10000头猪&#xff0c;该养猪场利用自己的种猪进行繁育。养猪的一般过程是&#xff1a;母猪配种后怀孕约114天产下乳猪&#xff0c;经过哺乳期后乳猪成为小猪。小猪的一部分将被选为种猪&#xff08;其中公…

20240727 影石 笔试

文章目录 1、选择题1.11.21.31.41.51.61.71.81.91.10 2、简答题2.12.22.32.42.52.62.72.8 3、编程题3.1 岗位&#xff1a;云台嵌入式工程师-2025校招 题型&#xff1a;10 道选择题&#xff0c;8 道简答题&#xff0c;1 道编程题 1、选择题 1.1 【多选】以下关于DMA的描述哪些…

Pytest中fixture含返回值时如何隐式自动应用?

在我们使用 Pytest 框架进行自动化测试时&#xff0c;强大的 fixture 夹具为框架的灵活应用提供了极大的便利。比如我们可以利用 fixture 的autouse属性&#xff0c;使它在测试方法的不同范围层级上自动生效。但如果要引用fixture的返回&#xff0c;我们通常还是要明确指定&…

FMEA 在智能制造中的应用与挑战_SunFMEA

【大家好&#xff0c;我是唐Sun&#xff0c;唐Sun的唐&#xff0c;唐Sun的Sun。一站式数智工厂解决方案服务商】 FMEA&#xff08;失效模式与影响分析&#xff09;在智能制造中具有重要的应用价值&#xff0c;但同时也面临着一系列的挑战。 应用&#xff1a; 产品设计优化 在…

react18+react-transition-group实现路由切换过度

效果如下 官网安装对应的插件 创建对应的样式 .fade-enter {opacity: 0; } .fade-exit {opacity: 1; } .fade-enter-active {opacity: 1; } .fade-exit-active {opacity: 0; } .fade-enter-active, .fade-exit-active {transition: opacity 500ms; }const location useLoca…

WSL(Windows Subsystem for Linux)——简单的双系统开发

文章目录 WSLWSL的作用WSL的使用WSL的安装挂载磁盘的作用安装linux发行版wsl下载mysql&#xff0c;mongodb&#xff0c;redis WSL 前言&#xff1a;本人由于在开发中需要linux环境&#xff0c;同时还想要直接在Windows下开发&#xff0c;来提升开发效率&#xff0c;随即简单学…

【问题分析】使用gperftools分析排查内存问题

背景 当程序长时间允许时(压测、服务器程序)&#xff0c;就会面临更大的挑战&#xff0c;其中内存泄漏就是一类典型的问题&#xff0c;内存泄漏往往不易发现&#xff0c;导致的现象更是千奇百怪&#xff0c;本文主要介绍如何借助gperftools分析一个模块的内存泄漏 案例代码 …

SpringBoot框架在高校竞赛管理中的创新应用

3系统分析 3.1可行性分析 通过对本高校学科竞赛平台实行的目的初步调查和分析&#xff0c;提出可行性方案并对其一一进行论证。我们在这里主要从技术可行性、经济可行性、操作可行性等方面进行分析。 3.1.1技术可行性 本高校学科竞赛平台采用SSM框架&#xff0c;JAVA作为开发语…

编译/引导EDK2 树莓派4

格蠹的幽兰代码本(RK3588)支持UEFI启动&#xff0c;在阅读RK3588代码的时候发现EDK2也对树莓派系列进行了支持。经过一番尝试&#xff0c;借助幽兰&#xff0c;我也在树莓派上bringup EFI bios(只能引导到Bios setup界面&#xff0c;不知道如何安装OS)&#xff0c;在此记录SOP。…

1.Label Studio 介绍

Label Studio 介绍 文章目录 Label Studio 介绍前言一、安装介绍二、Run with Docker Compose1、WSL2安装2、Docker Desktop安装3、Label Studio安装&#xff08;第二种方法 Run with Docker Compose &#xff09; 三、Install for local development1.下载源码2.安装poetry3.安…

YOLO11改进 | 注意力机制 | 用于增强小目标感受野的RFEM

秋招面试专栏推荐 &#xff1a;深度学习算法工程师面试问题总结【百面算法工程师】——点击即可跳转 &#x1f4a1;&#x1f4a1;&#x1f4a1;本专栏所有程序均经过测试&#xff0c;可成功执行&#x1f4a1;&#x1f4a1;&#x1f4a1; 近年来&#xff0c;基于深度学习的人脸检…

【计算机网络】计算机网络相关术语

文章目录 NAT概述NAT的基本概念NAT的工作原理1. **基本NAT&#xff08;静态NAT&#xff09;**2. **动态NAT**3. **NAPT&#xff08;网络地址端口转换&#xff0c;也称为PAT&#xff09;** 底层实现原理1. **数据包处理**2. **转换表**3. **超时机制** NAT的优点NAT的缺点总结 P…

vue3 高德地图标注(飞线,呼吸点)效果

装下这两个 npm 忘了具体命令了&#xff0c;百度一下就行 “loca”: “^1.0.1”, “amap/amap-jsapi-loader”: “^1.0.1”, <template><div id"map" style"width: 100%;height: 100%;"></div> </template><script setup> …

linux 下 verilog 简明开发环境附简单实例

author: hjjdebug date: 2024年 10月 12日 星期六 10:34:13 CST descripton: linux 下 verilog 简明开发环境附简单实例 甲: 安装软件 1. sudo apt install iverilog 该包verilog 源代码的编译器iverilog&#xff0c;其输出是可执行的仿真文件格式vvp格式 它可以检查源代码中…

ubuntu20.4环境下gcc-aarch64交叉编译器的安装

交叉编译器&#xff08;Linux环境&#xff09;arm gcc 8.3一共有5个版本&#xff0c;常用的有4个版本&#xff08;另外一个为大端linux版本&#xff09;&#xff0c;分别是32bit裸机版本&#xff08;arm-eabi&#xff09;、64bit裸机版本&#xff08;aarch64-elf&#xff09;、…

4. 单例模式线程安全问题--是否加锁

单例模式线程安全问题--是否加锁 是否加锁问题指什么&#xff1f;解决多线程并发来带的问题继承MonoBehaviour的单例模式不继承MonoBehaviour的单例模式 总结 是否加锁问题指什么&#xff1f; 如果程序当中存在多线程&#xff0c;我们需要考虑当多个线程同时访问同一个内存空间…

【Java】面向UDP接口的网络编程

【Java】面向UDP接口的网络编程 一. 基本通信模型二. APIDatagramSocketDatagramPacket 三. 回显服务器/客户端示例服务器客户端总结 一. 基本通信模型 UDP协议是面向数据报的&#xff0c;因此此处要构建数据报(Datagram)在进行发送。 二. API DatagramSocket DatagramSocke…

Ubuntu 24.04 在 BPI-F3 上通过 SD 卡安装并从 NVME 运行

github 代码&#xff1a; https://github.com/rcman/BPI-F3 Ubuntu 24.04 现在正在我的 BPI-F3 上运行。很快会为 YouTube 制作一个视频。 这应该适用于任何版本的 Linux&#xff0c;仅在 Ubuntu 24.04 上测试过 入门 下载 Bianbu映像并使用您最喜欢的工具将其映像到微型 SD 卡…

进程 vs 线程:你需要知道的关键区别

“大树根深&#xff0c;才能迎风而立。” 进程&#xff1a;计算机中正在执行的程序的实例&#xff0c;它是操作系统进行资源分配的基本单位。 通过写特殊代码&#xff0c;把多个 CPU 核心都能利用起来&#xff0c;这样的代码就称为“并发编程”。 虽然多进程能够解决问题&…