教你开发脚手架集成Spring Boot Actuator监控的详细过程

目录
  • 集成
    • 引入依赖
    • 配置文件
    • 访问验证
  • 端点 Endpoints
    • Health
    • Info
  • 安全
  • 高级
    • 自定义健康检查
    • 自定义metrics指标
    • PID PORT过程监控
    • 自定义管理端点路径
    • 自定义管理服务器端口
    • 暴露数据给Prometheus

集成

引入依赖

在项目的pom.xml中增加以下依赖

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

配置文件

application.yml

management:
   # 禁用执行器端点的安全检查
   security:
      enabled: false

访问验证

例如,输入http://localhost:8080/actuator/health,我们可以查看应用程序当前状态

{
    "status": "UP"
}

这个接口经常用于服务探活或者健康检查接口。

到这里就集成完成了哈。

端点 Endpoints

Actuator默认把所有访问点暴露给JMX,但处于安全原因,只有healthinfo会暴露给Web。

Actuator提供的所有访问点均在官方文档列出,要暴露更多的访问点给Web,需要在application.yml中加上配置:

management:
  endpoints:
    web:
      exposure:
        # 包含所有端点使用 "*",注意有引号
        include: info, health, beans, env, metrics

Actuator 提供了以下接口,具体如下表所示。

HTTP 方法 路径 描述
GET /auditevents 显示应用暴露的审计事件 (比如认证进入、订单失败)
GET /beans 描述应用程序上下文里全部的 Bean,以及它们的关系
GET /conditions 就是 1.0 的 /autoconfig ,提供一份自动配置生效的条件情况,记录哪些自动配置条件通过了,哪些没通过
GET /configprops 描述配置属性(包含默认值)如何注入Bean
GET /env 获取全部环境属性
GET /env/{name} 根据名称获取特定的环境属性值
GET /flyway 提供一份 Flyway 数据库迁移信息
GET /liquidbase 显示Liquibase 数据库迁移的纤细信息
GET /health 报告应用程序的健康指标,这些值由 HealthIndicator 的实现类提供
GET /heapdump dump 一份应用的 JVM 堆信息
GET /httptrace 显示HTTP足迹,最近100个HTTP request/repsponse
GET /info 获取应用程序的定制信息,这些信息由info打头的属性提供
GET /logfile 返回log file中的内容(如果 logging.file 或者 logging.path 被设置)
GET /loggers 显示和修改配置的loggers
GET /metrics 报告各种应用程序度量信息,比如内存用量和HTTP请求计数
GET /metrics/{name} 报告指定名称的应用程序度量值
GET /scheduledtasks 展示应用中的定时任务信息
GET /sessions 如果我们使用了 Spring Session 展示应用中的 HTTP sessions 信息
POST /shutdown 关闭应用程序,要求endpoints.shutdown.enabled设置为true
GET /mappings 描述全部的 URI路径,以及它们和控制器(包含Actuator端点)的映射关系
GET /threaddump 获取线程活动的快照
GET /prometheus 以 Prometheus 服务器可以抓取的格式公开指标。需要依赖micrometer-registry-prometheus.

下面着重讲下实际项目用到的。

Health

health 主要用来检查应用的运行状态,这是我们使用最高频的一个监控点。监控实例的运行状态,以及应用不”健康“的原因,比如数据库连接、磁盘空间不够等。

健康信息详情是否公开可以配置,例如:

management.endpoint.health.show-details=always
  • never 从不显示细节,默认
  • when-authorized 详细信息仅向授权用户显示。可以使用 配置授权角色management.endpoint.health.roles
  • always 向所有用户显示详细信息。

Spring Boot 会自动配置HealthIndicators下表中列出的内容。您也可以通过配置启用或禁用选定的指标management.health.key.enabledkey如下表所示:

钥匙 姓名 描述
cassandra CassandraDriverHealthIndicator 检查 Cassandra 数据库是否已启动。
couchbase CouchbaseHealthIndicator 检查 Couchbase 集群是否已启动。
db DataSourceHealthIndicator 检查是否可以获得连接DataSource
diskspace DiskSpaceHealthIndicator 检查磁盘空间不足。
elasticsearch ElasticsearchRestHealthIndicator 检查 Elasticsearch 集群是否已启动。
hazelcast HazelcastHealthIndicator 检查 Hazelcast 服务器是否已启动。
influxdb InfluxDbHealthIndicator 检查 InfluxDB 服务器是否已启动。
jms JmsHealthIndicator 检查 JMS 代理是否已启动。
ldap LdapHealthIndicator 检查 LDAP 服务器是否已启动。
mail MailHealthIndicator 检查邮件服务器是否已启动。
mongo MongoHealthIndicator 检查 Mongo 数据库是否已启动。
neo4j Neo4jHealthIndicator 检查 Neo4j 数据库是否已启动。
ping PingHealthIndicator 始终以 响应UP
rabbit RabbitHealthIndicator 检查 Rabbit 服务器是否已启动。
redis RedisHealthIndicator 检查 Redis 服务器是否已启动。
solr SolrHealthIndicator 检查 Solr 服务器是否已启动。

可以在配置文件中关闭特定的健康检查指标,比如关闭 redis 的健康检查:

management.health.redis.enabled=false

Info

info 就是我们自己配置在配置文件中以 info 开头的配置信息,您可以通过设置Spring 属性来自定义info端点公开的数据。info.*键下的所有Environment属性都会自动公开。例如,您可以将以下设置添加到application.yaml文件中:

info:
  app:
    name: spring-boot-actuator
    version: 1.0.0
    test: test
    encoding: @project.build.sourceEncoding@
    source: @java.version@
    target: @java.version@

启动项目,访问:http://localhost:8080/actuator/info返回部分信息如下:

{
	"app": {
		"name": "spring-boot-actuator",
		"version": "1.0.0",
		"test": "test",
		"encoding": "UTF-8",
		"source": "1.8.0_102",
		"target": "1.8.0_102"
	}
}

安全

要特别注意暴露的URL的安全性,例如,/actuator/env可以获取当前机器的所有环境变量,不可暴露给公网。

为了保证 actuator 暴露的监控接口的安全性,需要添加安全控制的依赖spring-boot-start-security依赖,访问应用监控端点时,都需要输入验证信息。

则默认情况下使用基于表单的HTTP身份验证来保护端点。

Security 依赖,可以选择不加,不进行安全管理,但不建议这么做。

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

代码如下:

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    /*
     * version1:
     * 1. 限制 '/shutdown'端点的访问,只允许ACTUATOR_ADMIN访问
     * 2. 允许外部访问其他的端点
     * 3. 允许外部访问静态资源
     * 4. 允许外部访问 '/'
     * 5. 其他的访问需要被校验
     * version2:
     * 1. 限制所有端点的访问,只允许ACTUATOR_ADMIN访问
     * 2. 允许外部访问静态资源
     * 3. 允许外部访问 '/'
     * 4. 其他的访问需要被校验
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // version1
//        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();

        // version2
        http
                .authorizeRequests()
                .requestMatchers(EndpointRequest.toAnyEndpoint())
                    .hasRole("ACTUATOR_ADMIN")
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                    .permitAll()
                .antMatchers("/")
                    .permitAll()
                .antMatchers("/**")
                    .authenticated()
                .and()
                .httpBasic();
    }
}

application.properties的相关配置如下:

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

高级

自定义健康检查

要提供自定义健康信息,您可以注册实现该HealthIndicator接口的 Spring bean。您需要提供该health()方法的实现并返回Health响应。Health响应应包含状态,并且可以选择包含要显示的其他详细信息。以下代码显示了一个示例HealthIndicator实现:

@Component
public class EasyAdminHealthIndicator extends AbstractHealthIndicator {
    @Override
    public void doHealthCheck(Health.Builder builder) throws Exception {
        boolean checkHealth = check();
        if (checkHealth) {
            builder.up();
        } else {
            builder.down();
        }
        builder.withDetail("code", "200")
                .withDetail("msg", "i am ok");
    }
    private boolean check() {
        return true;
    }
}

启动项目,访问:http://localhost:8080/actuator/health返回信息如下:

{
	"status": "UP",
	"components": {
		"db": {
			"status": "UP",
			"details": {
				"database": "MySQL",
				"validationQuery": "isValid()"
			}
		},
		"diskSpace": {
			"status": "UP",
			"details": {
				"total": 332861009920,
				"free": 312464228352,
				"threshold": 10485760,
				"exists": true
			}
		},
		"easyAdmin": {         // do do do
			"status": "UP",
			"details": {
				"code": "200",
				"msg": "i am ok"
			}
		},
		"mail": {
			"status": "UP",
			"details": {
				"location": "smtp.qq.com:-1"
			}
		},
		"ping": {
			"status": "UP"
		}
	}
}

自定义metrics指标

两种常用指标类型(Metric Type)

gauge, counter, summary, timer

gauge: 可增可减计数器,反应某值当前一刻状态。比如称重传感器的当前重量,温度传感器的当前温度。

方式一:

Gauge.builder("gn.temperature.gauge", new AtomicInteger(37), AtomicInteger::get)

方式二:

registry.gauge("gn.temperature.gauge", Tags.of("site", "SiteA", "cab", "cab01"), new AtomicInteger(37));

counter:只增不减计数器,是Gauge的一个特例。适用于只有服务器重启时候才会重置的计数场景。比如"用户访问次数",某接口失败次数"等等。API 使用方式类似。

Counter counter = Counter.builder("gn.beat.counter")
  .tags("site", "SiteA", "function", "foo")
  .description("for request errors")
  .register(registry);
counter.increment();

融入到系统的方式

方式一: 业务系统埋点

@Component
public class SampleBean {
    private final Counter counter;
    private final List<String> list = new CopyOnWriteArrayList<>();;
    public SampleBean(MeterRegistry registry) {
        this.counter = registry.counter("laker.counter");
         registry.gauge("laker.size", Tags.empty(), this.list.size());
    }
    public void handleMessage(String message) {
        this.counter.increment();
        list.add(message);
    }
    public void handleRemoveMessage(String message) {
        list.remove(message);
    }
}

方式二:MeterBinder

SpringBoot中提供了MeterBinder接口用于申明与注册meterRegistry。自定义Metrics只需要实现MeterBinder接口,Spring会自动发现并完成后续的杂活。

@Bean
public class MyMetrics implements MeterBinder {
   @Override
   public void bindTo(MeterRegistry meterRegistry) {
    //此处添加相关指标
    meterRegistry.gauge("laker.gauge", Tags.of("site", "SiteA"), new AtomicInteger(37));
   }
}

在浏览器访问http://localhost:8080/actuator/metrics/laker.counter

结果如下

{
    "name": "laker.counter",
    "description": null,
    "baseUnit": null,
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 9.0
        }
    ],
    "availableTags": []
}

其他使用情况可参考:MetricsAutoConfiguration.java

PID PORT过程监控

  • ApplicationPidFileWriter创建一个包含应用程序 PID 的文件(默认情况下,在应用程序目录中,文件名为application.pid)。
  • WebServerPortFileWriter创建一个文件(或多个文件),其中包含正在运行的 Web 服务器的端口(默认情况下,在应用程序目录中,文件名为application.port)。

默认情况下,这些编写器未激活:

@SpringBootApplication
public class LakerMapApplication {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(LakerMapApplication.class);
        springApplication.addListeners(new ApplicationPidFileWriter(), new WebServerPortFileWriter("./laker.port"));
        springApplication.run(args);
    }
}

配置文件:

spring:
  pid:
    # 写入pid的文件
    file: ./laker.pid
    # 当无法写入pid文件的时候,是否抛出异常
    fail-on-write-error: false

自定义管理端点路径

management.endpoints.web.base-path=/manage

将端点从/actuator/{id}更改为/manage/{id}(例如,/manage/info)。

如果要将端点映射到不同的路径,可以使用该management.endpoints.web.path-mapping属性。

以下示例重新映射/actuator/health/healthcheck

management.endpoints.web.base-path=/
management.endpoints.web.path-mapping.health=healthcheck

自定义管理服务器端口

management.server.port=8081
management.server.address=127.0.0.1

暴露数据给Prometheus

因为暴露内部信息的特性,Actuator 也可以和一些外部的应用监控系统整合(Prometheus, Graphite, DataDog, Influx, Wavefront, New Relic等)。这些监控系统提供了出色的仪表板,图形,分析和警报,可帮助你通过一个统一友好的界面,监视和管理你的应用程序。

添加依赖

为了让Spring Boot 应用和Prometheus 集成,你需要增加micrometer-registry-prometheus依赖。

<!-- Micrometer Prometheus registry  -->
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

添加上述依赖项之后,Spring Boot 将会自动配置 PrometheusMeterRegistryCollectorRegistry来以Prometheus 可以抓取的格式收集和导出指标数据。

所有的相关数据,都会在Actuator 的 /prometheus端点暴露出来。Prometheus 可以抓取该端点以定期获取度量标准数据。

添加micrometer-registry-prometheus依赖后,我们访问http://localhost:8080/actuator/prometheus地址。

参考:

https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/html/production-ready-features.html

https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html

https://segmentfault.com/a/1190000021611510

到此这篇关于教你集成Spring Boot Actuator监控开发脚手架的文章就介绍到这了,更多相关Spring Boot Actuator监控脚手架内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot 指标监控actuator的专题

    目录 1.写在前面 2.SpringBoot Actuator 3.定制化Endpoint 3.1 定制health端点信息 3.2 定制info端点信息 1.写在前面 首先肯定要说一下SpringBoot的四大核心了: 自动装配:简单配置甚至零配置即可运行项目 起步依赖:场景启动器 Actuator:指标监控 命令行界面 :命令行 这篇文章呢,我来和大家聊聊指标监控这个东西. 2.SpringBoot Actuator 未来每一个微服务在云上部署以后,我们都需要对其进行监控.追踪.审计.控制等

  • SpringBoot Actuator埋点和监控及简单使用

    目录 1. 数据埋点 2. Micrometer 2.1 简单使用 2.2 命名规范 3. SpringBoot Actuator 3.1 添加依赖 3.2 基础配置 3.3 查看可消费的端点 3.4 获取应用的基本信息 3.5 健康指标 3.6 指标端点 metrics 4. 实例 4.1 测试接口 4.2 消费指标端点 5. SpringBoot Admin 5.1 Admin 服务器端 5.1.1 启用功能.添加依赖 5.1.2 选择一个端口 5.1.3 访问 5.2 Client 客户端

  • 从零搭建Spring Boot脚手架整合OSS作为文件服务器的详细教程

    1. 前言 文件服务器是一个应用必要的组件之一.最早我搞过FTP,然后又用过FastDFS,接私活的时候我用MongoDB也凑合凑合.现如今时代不同了,开始流行起了OSS. Gitee: https://gitee.com/felord/kono day06 分支 欢迎Star GitHub: https://github.com/NotFound403/kono day06 分支 欢迎Star 2. 什么是OSS 全称为Object Storage Service,也叫对象存储服务,是一种解决

  • SpringBootAdmin+actuator实现服务监控

    SpringBootAdmin可以监控SpringBoot单击或集群项目,提供详细的健康信息.内存信息.JVM系统和环境属性.垃圾回收信息.日志设置和查看.定时任务查看.SpringBoot缓存查看和管理功能. 第一步:监控服务端搭建 创建一个SpringBoot项目,添加下面依赖 <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-st

  • springboot Actuator的指标监控可视化功能详解

    springboot为我们提供了丰富的指标监控功能SpringBoot Actuator SpringBoot Actuator是springboot为简化我们对微服务项目的监控功能抽取出来的模块,使得我们每个微服务快速引用即可获得生产界别的应用监控.审计等功能. 后序文章会更新使用 我们先来看看怎么可视化 我们可以通过github上的开源项目 这里 我们创建一个springboot项目 作为可视化的服务端 使用新功能首先都是引入依赖 需要web项目 <dependency> <grou

  • spring boot actuator监控超详细教程

    spring boot actuator介绍 Spring Boot包含许多其他功能,可帮助您在将应用程序推送到生产环境时监视和管理应用程序. 您可以选择使用HTTP端点或JMX来管理和监视应用程序. 审核,运行状况和指标收集也可以自动应用于您的应用程序. 总之Spring Boot Actuator就是一款可以帮助你监控系统数据的框架,其可以监控很多很多的系统数据,它有对应用系统的自省和监控的集成功能,可以查看应用配置的详细信息,如: 显示应用程序员的Health健康信息 显示Info应用信息

  • 阿里云发布 Spring Boot 新脚手架工程

    背景 相信很多人都使用过 start.spring.io 来初始化自己的 Spring Boot 工程,这个工具为开发者提供了丰富的可选组件,并且可以选择多种打包方式,大大方便了开发人员的使用.最近,阿里的 Nacos.Sentinel 也进入 start.spring.io 的选项中,进一步的方便开发者使用阿里云的产品. 但是,生成的工程骨架中,只有组件坐标信息,缺少对应的使用方法和 Demo 代码:于是,开发者还是需要去寻找相关使用教程,或者样例代码:如果找的不对,或者是版本不匹匹配,还需要

  • 教你开发脚手架集成Spring Boot Actuator监控的详细过程

    目录 集成 引入依赖 配置文件 访问验证 端点 Endpoints Health Info 安全 高级 自定义健康检查 自定义metrics指标 PID PORT过程监控 自定义管理端点路径 自定义管理服务器端口 暴露数据给Prometheus 集成 引入依赖 在项目的pom.xml中增加以下依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-

  • Spring Boot Actuator监控端点小结

    在Spring Boot的众多Starter POMs中有一个特殊的模块,它不同于其他模块那样大多用于开发业务功能或是连接一些其他外部资源.它完全是一个用于暴露自身信息的模块,所以很明显,它的主要作用是用于监控与管理,它就是:spring-boot-starter-actuator. spring-boot-starter-actuator模块的实现对于实施微服务的中小团队来说,可以有效地减少监控系统在采集应用指标时的开发量.当然,它也并不是万能的,有时候我们也需要对其做一些简单的扩展来帮助我们

  • springboot 使用Spring Boot Actuator监控应用小结

    微服务的特点决定了功能模块的部署是分布式的,大部分功能模块都是运行在不同的机器上,彼此通过服务调用进行交互,前后台的业务流会经过很多个微服务的处理和传递,出现了异常如何快速定位是哪个环节出现了问题? 在这种框架下,微服务的监控显得尤为重要.本文主要结合Spring Boot Actuator,跟大家一起分享微服务Spring Boot Actuator的常见用法,方便我们在日常中对我们的微服务进行监控治理. Actuator监控 Spring Boot使用"习惯优于配置的理念",采用包

  • Spring Boot集成 Spring Boot Admin 监控

    [前言] 程序开发完实现相应的功能只是一个部分,如何让系统在线上运行更好创造更高的价值是另外一个部分:监控是一个生产级项目避不可少重要组成部分:最近研究一下针对SpringBoot的监控项目---Spring Boot Admin,并集成项目中,在此与大家共享: [SpringBootAdmin] 一.SpringBootAdmin简介 1.github地址:https://github.com/codecentric/spring-boot-admin 2.重要功能列表: 二.项目中集成Spr

  • Spring Boot Actuator监控的简单使用方法示例代码详解

    Spring Boot Actuator帮助我们实现了许多中间件比如mysql.es.redis.mq等中间件的健康指示器. 通过 Spring Boot 的自动配置,这些指示器会自动生效.当这些组件有问题的时候,HealthIndicator 会返回 DOWN 或 OUT_OF_SERVICE 状态,health 端点 HTTP 响应状态码也会变为 503,我们可以以此来配置程序健康状态监控报警. 使用步骤也非常简单,这里演示的是线程池的监控.模拟线程池满了状态下将HealthInicator

  • Spring Boot应用监控的实战教程

    概述 Spring Boot 监控核心是 spring-boot-starter-actuator 依赖,增加依赖后, Spring Boot 会默认配置一些通用的监控,比如 jvm 监控.类加载.健康监控等. 我们之前讲过Docker容器的可视化监控,即监控容器的运行情况,包括 CPU使用率.内存占用.网络状况以及磁盘空间等等一系列信息.同样利用SpringBoot作为微服务单元的实例化技术选型时,我们不可避免的要面对的一个问题就是如何实时监控应用的运行状况数据,比如:健康度.运行指标.日志信

  • 在Docker中开发Java 8 Spring Boot应用程序的方法

    在本文中,我将向您展示如何使用Java 8开发和运行简单的Spring Web应用程序,而无需在本地计算机上安装Java 8. Python开发人员使用虚拟环境为不同项目创建和管理单独的环境,每个环境使用不同版本的Python来执行,存储和解析Python依赖项.Java和许多其他技术不支持虚拟环境概念.在这一点上,Docker来帮助我们. Docker是一个虚拟化平台.您可以从Docker官方网站上找到基本信息和安装指南. 一旦安装了Docker工具箱,就不需要安装我们的示例应用程序中所需的J

  • Spring Boot Actuator执行器运行原理详解

    Spring Boot执行器(Actuator)提供安全端点,用于监视和管理Spring Boot应用程序. 默认情况下,所有执行器端点都是安全的. 在本章中,将详细了解如何为应用程序启用Spring Boot执行器. 启用Spring Boot Actuator 要为Spring Boot应用程序启用Spring Boot执行器端点,需要在构建配置文件中添加Spring Boot Starter执行器依赖项. Maven用户可以在pom.xml 文件中添加以下依赖项. <dependency>

  • Spring Boot Actuator端点相关原理解析

    Spring Boot Actuator的关键特性是在应用程序里提供众多Web端点,通过它们了解应用程序 运行时的内部状况.有了Actuator,你可以知道Bean在Spring应用程序上下文里是如何组装在一起的,掌握应用程序可以获取的环境属性信息,获取运行时度量信息的快照-- Actuator提供13个端点,可以分为三大类:配置端点.度量端点和其他端点.具体如下表所示: Http方法 路径 描述 get /autoconfig 提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过 g

随机推荐