Spring Boot Actuator解析

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: Actuator 是 SpringBoot 项目中一个非常强大一个功能,有助于对应用程序进行监视和管理,通过 Restful Api 请求来监管、审计、收集应用的运行情况。

       Actuator 是 SpringBoot 项目中一个非常强大一个功能,有助于对应用程序进行监视和管理,通过 Restful Api 请求来监管、审计、收集应用的运行情况。

       Actuator 的核心是端点 Endpoint,它用来监视应用程序及交互,Spring-Boot-Actuator 目前已经内置了非常多的 Endpoint(health、info、beans、metrics、httptrace、shutdown等等),同时也允许我们自己扩展自己的 Endpoints。每个 Endpoint 都可以启用和禁用。要远程访问 Endpoint,还必须通过 JMX 或 HTTP 进行暴露,大部分应用选择HTTP,Endpoint 的ID默认映射到一个带 /actuator 前缀的URL。例如,Health 端点默认映射到 /actuator/health。

     除此,Actuator同时还可以与外部应用监控系统整合,比如 Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic等。这些系统提供了非常好的仪表盘、图标、分析和告警等功能,使得你可以通过统一的接口轻松的监控和管理你的应用。    

Actuator使用

      启用Actuator功能,最直接的方式是添加 spring-boot-starter-actuator ‘Starter’依赖      

1、pom.xml

<!-- 2、监控 —— Actuator插件 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

 

2、application.yml 或application.properties

management:
  endpoints:
    # 暴露 EndPoint 以供访问,有jmx和web两种方式,exclude 的优先级高于 include
    jmx:
      exposure:
        exclude: '*'
        include: '*'
    web:
      exposure:
      # exclude: '*'
        include: ["health","info","beans","mappings","logfile","metrics","shutdown","env"]
      base-path: /actuator  # 配置 Endpoint 的基础路径
      cors: # 配置跨域资源共享
        allowed-origins: http://example.com
        allowed-methods: GET,POST
    enabled-by-default: true # 修改全局 endpoint 默认设置
  endpoint:
    auditevents: # 1、显示当前引用程序的审计事件信息,默认开启
      enabled: true
      cache:
        time-to-live: 10s # 配置端点缓存响应的时间
    beans: # 2、显示一个应用中所有 Spring Beans 的完整列表,默认开启
      enabled: true
    conditions: # 3、显示配置类和自动配置类的状态及它们被应用和未被应用的原因,默认开启
      enabled: true
    configprops: # 4、显示一个所有@ConfigurationProperties的集合列表,默认开启
      enabled: true
    env: # 5、显示来自Spring的 ConfigurableEnvironment的属性,默认开启
      enabled: true
    flyway: # 6、显示数据库迁移路径,如果有的话,默认开启
      enabled: true
    health: # 7、显示健康信息,默认开启
      enabled: true
      show-details: always
    info: # 8、显示任意的应用信息,默认开启
      enabled: true
    liquibase: # 9、展示任何Liquibase数据库迁移路径,如果有的话,默认开启
      enabled: true
    metrics: # 10、展示当前应用的metrics信息,默认开启
      enabled: true
    mappings: # 11、显示一个所有@RequestMapping路径的集合列表,默认开启
      enabled: true
    scheduledtasks: # 12、显示应用程序中的计划任务,默认开启
      enabled: true
    sessions: # 13、允许从Spring会话支持的会话存储中检索和删除(retrieval and deletion)用户会话。使用Spring Session对反应性Web应用程序的支持时不可用。默认开启。
      enabled: true
    shutdown: # 14、允许应用以优雅的方式关闭,默认关闭
      enabled: true
    threaddump: # 15、执行一个线程dump
      enabled: true
    # web 应用时可以使用以下端点
    heapdump: # 16、    返回一个GZip压缩的hprof堆dump文件,默认开启
      enabled: true
    jolokia: # 17、通过HTTP暴露JMX beans(当Jolokia在类路径上时,WebFlux不可用),默认开启
      enabled: true
    logfile: # 18、返回日志文件内容(如果设置了logging.file或logging.path属性的话),支持使用HTTP Range头接收日志文件内容的部分信息,默认开启
      enabled: true
    prometheus: #19、以可以被Prometheus服务器抓取的格式显示metrics信息,默认开启
      enabled: true

       以简单的项目为例,简要讲解下Actuator功能的相关配置及具体实现,具体如下:

      构建完项目后进行启动,应用程序默认以端口8080运行,上图表面程序启动正常,可直接通过Uri访问以获取指定暴露的Endpoints。

      通过访问http://localhost:8080/actuator来展示所有通过HTTP暴露的Endpoints:


[administrator@JavaLangOutOfMemory java ]% curl http://localhost:8080/actuator
{"_links":{"self":{"href":"http://localhost:8080/actuator","templated":false},"auditevents":{"href":"http://localhost:8080/actuator/auditevents","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-component":{"href":"http://localhost:8080/actuator/health/{component}","templated":true},"health-component-instance":{"href":"http://localhost:8080/actuator/health/{component}/{instance}","templated":true},"health":{"href":"http://localhost:8080/actuator/health","templated":false},"conditions":{"href":"http://localhost:8080/actuator/conditions","templated":false},"shutdown":{"href":"http://localhost:8080/actuator/shutdown","templated":false},"configprops":{"href":"http://localhost:8080/actuator/configprops","templated":false},"env":{"href":"http://localhost:8080/actuator/env","templated":false},"env-toMatch":{"href":"http://localhost:8080/actuator/env/{toMatch}","templated":true},"info":{"href":"http://localhost:8080/actuator/info","templated":false},"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":{"href":"http://localhost:8080/actuator/metrics","templated":false},"metrics-requiredMetricName":{"href":"http://localhost:8080/actuator/metrics/{requiredMetricName}","templated":true},"scheduledtasks":{"href":"http://localhost:8080/actuator/scheduledtasks","templated":false},"httptrace":{"href":"http://localhost:8080/actuator/httptrace","templated":false},"mappings":{"href":"http://localhost:8080/actuator/mappings","templated":false}}}%


      打开http://localhost:8080/actuator/health,则会显示如下内容:


[administrator@JavaLangOutOfMemory java ]% curl http://localhost:8080/actuator/health
{"status":"UP","details":{"diskSpace":{"status":"UP","details":{"total":100790001664,"free":94206066688,"threshold":10485760}}}}%


      请求结果状态若为UP,表明应用是健康的。如果应用不健康将会显示DOWN,比如与仪表盘的连接异常或者缺水磁盘空间等。

      打开http://localhost:8080/actuator/metrics,则会显示如下内容:


[administrator@JavaLangOutOfMemory java ]% curl -i http://localhost:8080/actuator/metrics
HTTP/1.1 200
Content-Type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 10 Jan 2021 01:59:29 GMT
{"names":["jvm.memory.max","jvm.threads.states","process.files.max","jvm.gc.memory.promoted","tomcat.cache.hit","tomcat.servlet.error","system.load.average.1m","tomcat.cache.access","jvm.memory.used","jvm.gc.max.data.size","jvm.gc.pause","jvm.memory.committed","system.cpu.count","logback.events","http.server.requests","tomcat.global.sent","jvm.buffer.memory.used","tomcat.sessions.created","jvm.threads.daemon","system.cpu.usage","jvm.gc.memory.allocated","tomcat.global.request.max","tomcat.global.request","tomcat.sessions.expired","jvm.threads.live","jvm.threads.peak","tomcat.global.received","process.uptime","tomcat.sessions.rejected","process.cpu.usage","tomcat.threads.config.max","jvm.classes.loaded","jvm.classes.unloaded","tomcat.global.error","tomcat.sessions.active.current","tomcat.sessions.alive.max","jvm.gc.live.data.size","tomcat.servlet.request.max","tomcat.threads.current","tomcat.servlet.request","process.files.open","jvm.buffer.count","jvm.buffer.total.capacity","tomcat.sessions.active.max","tomcat.threads.busy","process.start.time"]}% 



      以下整理了一些非常有用的Actuator Endpoints列表。完整的可以在official documentation上面获取。

Endpoint ID Description
auditevents 显示应用暴露的审计事件 (比如认证进入、订单失败)

info

显示应用的基本信息

health


显示应用的健康状态

metrics

显示应用多样的度量信息

loggers


显示和修改配置的loggers

logfile



返回log file中的内容(如果logging.file或者logging.path被设置)

httptrace



显示HTTP足迹,最近100个HTTP request/repsponse

env

显示当前的环境特性

flyway


显示数据库迁移路径的详细信息

liquidbase


显示Liquibase 数据库迁移的纤细信息

shutdown

让你逐步关闭应用

mappings


显示所有的@RequestMapping路径

scheduledtasks

显示应用中的调度任务

threaddump

heapdump

执行一个线程dump

返回一个GZip压缩的JVM堆dump

     

Actuator Endpoint解析

       /health endpoint

       Health Endpoint通过合并几个健康指数检查应用的健康情况。

       Spring Boot Actuator有几个预定义的健康指标比如DataSourceHealthIndicator, DiskSpaceHealthIndicator, MongoHealthIndicator, RedisHealthIndicator, CassandraHealthIndicator等。它使用这些健康指标作为健康检查的一部分。

       打个比方,如果你的应用使用Redis,RedisHealthindicator将被当作检查的一部分。如果使用MongoDB,那么MongoHealthIndicator将被当作检查的一部分。你也可以关闭特定的健康检查指标,比如在properties或yml文件中使用如下命令:


management.health.redis.enabled=false

       Health Endpoint只展示了简单的UP和DOWN状态。为了获得健康检查中所有指标的详细信息,可以通过在application.yaml中增加如下内容:


management:
  endpoint:
    health:
      show-details: always

      当然,如果觉得自带的不能够满足我们的实际业务场景,可以通过实现HealthIndicator接口来自定义一个健康指标,或者继承AbstractHealthIndicator类。具体如下:


package com.example.actuator.health;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthIndicator extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        // Use the builder to build the health status details that should be reported.
        // If you throw an exception, the status will be DOWN with the exception message.
        builder.up()
                .withDetail("app", "Alive and Kicking")
                .withDetail("error", "No!");
    }
}

       一旦你增加上面的健康指标到你的应用中去后,Health Endpoint将展示如下细节:


{
   "status":"UP",
   "details":{
      "custom":{
         "status":"UP",
         "details":{
            "app":"Alive and Kicking",
            "error":"No!"
         }
      },
      "diskSpace":{
         "status":"UP",
         "details":{
            "total":250790436864,
            "free":97949245440,
            "threshold":10485760
         }
      }
   }
}

       

Spring Security引入

       Actuator Eendpoints是敏感的,必须对其安全性进行可控。如果Spring Security是包含在你的应用中,那么Endpoint是通过HTTP认证被保护起来。如果没有, 可以增加以下依赖到应用中:


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


      通过以下示例简要展示一个简单的Spring Securiy配置。它借助EndPointRequest

的ReqeustMatcher工厂模式来配置Actuator Endpoints进入规则。具体如下:


package com.example.actuator.config;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
    /*
        This spring security configuration does the following
        1. Restrict access to the Shutdown endpoint to the ACTUATOR_ADMIN role.
        2. Allow access to all other actuator endpoints.
        3. Allow access to static resources.
        4. Allow access to the home page (/).
        5. All other requests need to be authenticated.
        5. Enable http basic authentication to make the configuration complete.
           You are free to use any other form of authentication.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
                        .hasRole("ACTUATOR_ADMIN")
                    .requestMatchers(EndpointRequest.toAnyEndpoint())
                        .permitAll()
                    .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                        .permitAll()
                    .antMatchers("/")
                        .permitAll()
                    .antMatchers("/**")
                        .authenticated()
                .and()
                .httpBasic();
    }
}

       然后在application.yaml文件中定义Spring Security用户,具体如下:


# Spring Security Default user name and password
spring:
  security:
    user:
      name: actuator
      password: actuator
      roles: ACTUATOR_ADMIN

       至此,Actuator监控功能的讲解到此为止,若您在使用过程中有任何的想法或建议,欢迎留言进行技术交流。


相关文章
|
2月前
|
缓存 安全 Java
Spring Security通用权限管理模型解析
Spring Security作为Spring生态的核心安全框架,结合RBAC与ACL权限模型,基于IoC与AOP构建灵活、可扩展的企业级权限控制体系,涵盖认证、授权流程及数据库设计、性能优化等实现策略。
233 0
|
2月前
|
缓存 安全 Java
Spring Security权限管理解析
Spring Security是Spring生态中的核心安全框架,采用认证与授权分离架构,提供高度可定制的权限管理方案。其基于过滤器链实现认证流程,通过SecurityContextHolder管理用户状态,并结合RBAC模型与动态权限决策,支持细粒度访问控制。通过扩展点如自定义投票器、注解式校验与前端标签,可灵活适配多租户、API网关等复杂场景。结合缓存优化与无状态设计,适用于高并发与前后端分离架构。
249 0
|
2月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
1月前
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
1月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
1月前
|
XML JSON Java
【SpringBoot(三)】从请求到响应再到视图解析与模板引擎,本文带你领悟SpringBoot请求接收全流程!
Springboot专栏第三章,从请求的接收到视图解析,再到thymeleaf模板引擎的使用! 本文带你领悟SpringBoot请求接收到渲染的使用全流程!
196 3
|
2月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
786 1
|
2月前
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
416 0
|
2月前
|
安全 Java 数据安全/隐私保护
Spring Security 核心技术解析与实践指南
本文档深入探讨 Spring Security 框架的核心架构、关键组件和实际应用。作为 Spring 生态系统中负责安全认证与授权的关键组件,Spring Security 为 Java 应用程序提供了全面的安全服务。本文将系统介绍其认证机制、授权模型、过滤器链原理、OAuth2 集成以及最佳实践,帮助开发者构建安全可靠的企业级应用。
190 0
|
4月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
877 0

推荐镜像

更多
  • DNS
  • 下一篇
    oss云网关配置