当前位置: 首页 > article >正文

学技术学英文:SpringBoot的内置监控组件-Spring Boot Actuator

导读:

Spring Boot Actuator是Spring Boot提供的一个模块,简单配置后就能开启,属于拿来即用,具体功能如下:

监控和管理Spring Boot应用

Spring Boot Actuator提供了一组REST端点和命令行工具,用于查看应用的运行状态、性能指标和健康状况等。通过这些端点,开发人员可以方便地获取应用的各类信息,如:健康检查、度量和指标、环境信息

应用度量数据的导出

Spring Boot Actuator支持将应用的运行数据导出到各种不同的存储后端,例如Prometheus、Datadog、New Relic等。这样,开发人员可以方便地使用这些数据来进一步分析和监控应用的性能和健康状况。

自定义端点和安全控制

发人员可以根据自己的需求来暴露自定义的监控数据,为了安全还支持限制访问权限、身份验证

其他工具的集成

Spring Boot Actuator可以与多种外部监控工具集成,如Prometheus和Grafana,进行更高级别的应用监控和管理。通过添加Micrometer和Prometheus依赖,可以将Actuator的指标数据导出到Prometheus,并使用Grafana进行可视化展示。

Introduction

Spring Boot Actuator is a sub-project of Spring Boot that provides a set of built-in production-ready features to help you monitor and manage your application. Actuator includes several endpoints that allow you to interact with the application, gather metrics, check the health, and perform various management tasks.

In this article, we will delve into the features of Spring Boot Actuator, how to set it up, and provide examples to demonstrate its capabilities.

Setting Up Spring Boot Actuator

To get started with Spring Boot Actuator, you need to add the `spring-boot-starter-actuator` dependency to your project. If you’re using Maven, add the following to your `pom.xml` file:

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

For Gradle, add the following line to your `build.gradle` file:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

Configuring Actuator Endpoints

By default, Actuator endpoints are exposed over HTTP. You can configure which endpoints are enabled and how they are accessed in your `application.properties` or `application.yml` file.

Here’s an example configuration in `application.properties`:

management.endpoints.web.exposure.include=health,info
management.endpoint.health.show-details=always

In `application.yml`:

management:
  endpoints:
    web:
      exposure:
        include: health, info
  endpoint:
    health:
      show-details: always

Common Actuator Endpoints

Spring Boot Actuator provides a variety of built-in endpoints. Below are some of the most commonly used ones:

/actuator/health: Displays the health status of the application.
/actuator/info: Displays arbitrary application information.
/actuator/metrics: Shows ‘metrics’ information for the current application.
/actuator/env: Displays properties from the `Environment`.
/actuator/beans: Displays a complete list of all Spring beans in your application.

Example: Health Endpoint

The health endpoint provides basic information about the application’s health. To access it, navigate to `/actuator/health` in your browser or use a tool like `curl`:

curl http://localhost:8080/actuator/health

The response will look something like this:

{
 "status": "UP"
}

You can add custom health indicators to include more detailed information. For example:

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

@Component
public class CustomHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // Custom health check logic
        boolean isHealthy = checkCustomHealth();
        if (isHealthy) {
            return Health.up().withDetail("CustomHealth", "All systems are operational").build();
        } else {
            return Health.down().withDetail("CustomHealth", "Some systems are down").build();
        }
    }

    private boolean checkCustomHealth() {
        // Implement your custom health check logic
        return true;
    }
}

Metrics and Monitoring

The `/actuator/metrics` endpoint provides various application metrics. For example, to see JVM memory usage, you can query:

curl http://localhost:8080/actuator/metrics/jvm.memory.used

The response will look like this:

{
  "name": "jvm.memory.used",
  "description": "The amount of used memory",
  "baseUnit": "bytes",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 567123456
    }
  ],
  "availableTags": [
    {
      "tag": "area",
      "values": [
        "heap",
        "nonheap"
      ]
    },
    {
      "tag": "id",
      "values": [
        "G1 Eden Space",
        "G1 Old Gen",
        "G1 Survivor Space",
        "Metaspace",
        "Compressed Class Space"
      ]
    }
  ]
}

Customizing Actuator Endpoints

You can create custom endpoints by implementing the `Endpoint` interface. Here’s an example of a custom endpoint that returns a simple message:

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

@Component
@Endpoint(id = "custom")
public class CustomEndpoint {

    @ReadOperation
    public String customEndpoint() {
        return "This is a custom endpoint";
    }
}

This endpoint can be accessed at `/actuator/custom`.

Securing Actuator Endpoints

By default, all Actuator endpoints are unsecured. In a production environment, it is crucial to secure them. You can do this using Spring Security. First, add the Spring Security dependency:

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

Then, configure security in your `application.properties`:

management.endpoints.web.exposure.include=health,info
management.endpoint.health.show-details=always
management.endpoints.web.base-path=/actuator

And create a security configuration class:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/actuator/**").authenticated()
            .and()
            .httpBasic();
    }
}

This configuration requires authentication for all Actuator endpoints and uses basic authentication.

Conclusion

Spring Boot Actuator is a powerful tool for monitoring and managing your application. It provides numerous built-in endpoints to check the application’s health, gather metrics, and perform various management tasks. By understanding how to configure and use these endpoints, you can ensure your application runs smoothly and efficiently.

By integrating custom health indicators, custom endpoints, and securing these endpoints using Spring Security, you can tailor Actuator to meet your specific needs. Whether you’re in development or production, Spring Boot Actuator is an invaluable component of the Spring Boot ecosystem.


http://www.kler.cn/a/446640.html

相关文章:

  • Golong中无缓冲的 channel 和 有缓冲的 channel 的区别
  • 在Java虚拟机(JVM)中,方法可以分为虚方法和非虚方法。
  • Windows server 服务器网络安全管理之防火墙出站规则设置
  • 3D Gaussian Splatting for Real-Time Radiance Field Rendering-简洁版
  • 基于Python3编写的Golang程序多平台交叉编译自动化脚本
  • 本地缓存和Redis缓存 存储更新时间的更新套路
  • Android 10 Launcher3 删除谷歌搜索
  • c++中如何处理对象的创建与销毁的时机?
  • Python发送带key的kafka消息
  • TCP为什么需要三次握手和四次挥手?
  • 创新性融合丨卡尔曼滤波+目标检测 新突破!
  • C/C++语言基础--C++STL库之仿函数、函数对象、bind、function简介
  • 单元测试(C++)——gmock通用测试模版(个人总结)
  • Spring(三)-SpringWeb-概述、特点、搭建、运行流程、组件、接受请求、获取请求数据、特殊处理、拦截器
  • python实现word转html
  • AI大模型进一步推动了AI在处理图片、视频、音频、文本的等数据应用
  • 【新教程】非root用户给Ubuntu server设置开机自启服务-root用户给Ubuntu server设置开机自启服务
  • ArcGIS计算土地转移矩阵
  • 详细解释爬虫中的异常处理机制?
  • Rabbitmq实现延迟队列
  • Leetcode2545:根据第 K 场考试的分数排序
  • 26、基于SpringBoot的在线文档管理系统的设计与实现
  • R 基础运算
  • 基于卷积神经网络(CNN)和ResNet50的水果与蔬菜图像分类系统
  • 机器视觉检测相机基础知识 | 颜色 | 光源 | 镜头 | 分辨率 / 精度 / 公差
  • Leetcode 串联所有单词的子串