Spring Boot学习笔记(六):Spring Boot 应用监控

Spring Boot 提供了运行时的应用监控和管理功能,我们可以通过http、JMX进行操作。

全部章节传送门:
Spring Boot学习笔记(一):Spring Boot 入门基础
Spring Boot学习笔记(二):Spring Boot 运行原理
Spring Boot学习笔记(三):Spring Boot Web开发
Spring Boot学习笔记(四):Spring Boot 数据访问
Spring Boot学习笔记(五):Spring Boot 企业级开发
Spring Boot学习笔记(六):Spring Boot 应用监控

常见端点介绍

Spring Boot 2.0提供的常用端点如下所示。

序号端点名描述默认开启(Web)默认开启(JMX)
1actuator所有端点的列表,需加入spring HATEOAS支持
2auditevents显示应用暴露的审计事件 (比如认证进入、订单失败)
3info显示应用的基本信息
4health显示应用的健康状态
5metrics显示应用多样的度量信息
6loggers显示和修改配置的loggers
7logfile返回log file中的内容(如果logging.file或者logging.path被设置)不适用
8httptrace显示HTTP足迹,最近100个HTTP request/repsponse
9env显示当前的环境特性
10flyway显示数据库迁移路径的详细信息
11shutdown让你逐步关闭应用
12mappings显示所有的@RequestMapping路径
13scheduledtasks显示应用中的调度任务
14threaddump执行一个线程dump不适用
15heapdump返回一个GZip压缩的JVM堆dump不适用

配置端点

默认情况下,所有的端点都是打开的,除了 shutdown 端点。可以通过 management.endpoint.<id>.enabled的值设置为true或者false

例如,想要打开 shutdown 端点,可以在application.properties中配置:

management.endpoint.shutdown.enabled=true

默认情况下,所有的端点都可以通过JMX查看,而只有health端点和info端点可以通过HTTP查看。我们可以通过配置进行修改。

management.endpoints.web.exposure.include=health,info 
management.endpoints.web.exposure.exclude=
management.endpoints.jmx.exposure.include=*
management.endpoints.jmx.exposure.exclude=

查看端点

创建 Spring Boot 项目,添加 Actuator、Web和HATEOAS依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wyk</groupId>
    <artifactId>actuatordemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>actuatordemo</name>
    <description>Demo project for Spring Boot Actustor</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在application.properties中添加配置信息。

# 开启所有端点允许HTTP查看
management.endpoints.web.exposure.include=*
# 显示详细健康信息
management.endpoint.health.show-details=always

然后运行程序,即可查看端点信息。

登录 http://localhost:8080/actuator

actuator端点查看.png

登录 http://localhost:8080/actuator/health 查看端点信息。

health端点查看.png

除了shutdown端点需要POST方式查看,其他端点均可直接查看。

还可以通过JMX对应用进行管理和监控。在控制台输入 jconsole即可进入JMX。

然后选择我们的程序进入界面,然后在MBean标签的org.springframework.boot域下可以对程序进行监控和管理。

jmx界面.png

自定义端点

自定义端点需要使用如下注释。

  • @Endpoint 是构建 rest 的唯一路径。不同请求的操作,调用时缺少必需参数,或者使用无法转换为所需类型的参数,则不会调用操作方法,响应状态将为400(错误请求)
  • @ReadOperation = GET 响应状态为 200 如果没有返回值响应 404(资源未找到)。
  • @WriteOperation = POST 响应状态为 200 如果没有返回值响应 204(无响应内容)
  • @DeleteOperation = DELETE 响应状态为 200 如果没有返回值响应 204(无响应内容)

依旧使用上面的工程,添加一个实体类。

package com.wyk.actuatordemo;

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

@Endpoint(id="status")
@Component
public class StatusEndpoint {
    private String status;

    @ReadOperation
    public String getStatus() {
        return status;
    }

    @WriteOperation
    public void setStatus(String status) {
        this.status = status;
    }
}

然后修改运行类。

package com.wyk.actuatordemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class ActuatordemoApplication {

    @Autowired
    StatusEndpoint statusEndpoint;

    public static void main(String[] args) {
        SpringApplication.run(ActuatordemoApplication.class, args);
    }

    @RequestMapping("/change")
    public String changeStatus(String status) {
        //StatusEndpoint statusEndpoint = new StatusEndpoint();
        statusEndpoint.setStatus(status);
        return "OK";
    }
}

运行程序,打开 http://localhost:8080/actuator/status, 这时候会报404,是因为status没有值。

自定义端点状态1.png

再打开一个窗口,输入 http://localhost:8080/change?status=123 , 这时候再打开 http://localhost:8080/actuator/status ,就可以看到了。

自定义端点状态2.png

自定义 HealthIndicator

Health 信息是从 AppliciationContext 中所有的 HealthIndicator 的 Bean 中收集的, Spring 内置的HealthIndicator 如下所示。

名称描述
CassandraHealthIndicator检查 Cassandra 数据库是否启动。
DiskSpaceHealthIndicator检查磁盘空间不足。
DataSourceHealthIndicator检查是否可以获得连接 DataSource。
ElasticsearchHealthIndicator检查 Elasticsearch 集群是否启动。
InfluxDbHealthIndicator检查 InfluxDB 服务器是否启动。
JmsHealthIndicator检查 JMS 代理是否启动。
MailHealthIndicator检查邮件服务器是否启动。
MongoHealthIndicator检查 Mongo 数据库是否启动。
Neo4jHealthIndicator检查 Neo4j 服务器是否启动。
RabbitHealthIndicator检查 Rabbit 服务器是否启动。
RedisHealthIndicator检查 Redis 服务器是否启动。
SolrHealthIndicator检查 Solr 服务器是否已启动。

要实现自己的 HealthIndicator 只需要实现 HealthIndicator 类。

package com.wyk.actuatordemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;

public class StatusHealth implements HealthIndicator {
    @Autowired
    StatusEndpoint statusEndpoint;

    @Override
    public Health health() {
        String status = statusEndpoint.getStatus();

        if(status == null || !status.equals("123")) {
            return Health.down().withDetail("Error", "Not Running").build();
        }
        return  Health.up().build();


    }
}

运行程序,打开 http://localhost:8080/actuator/health 查看。

自定义health.png



作者:简单一点点
链接:https://www.jianshu.com/p/f540d6e6b264
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值