Spring Boot學習筆記(六):Spring Boot 應用監(jiān)控

Spring Boot 提供了運行時的應用監(jiān)控和管理功能,我們可以通過http、JMX進行操作。

全部章節(jié)傳送門:
Spring Boot學習筆記(一):Spring Boot 入門基礎(chǔ)
Spring Boot學習筆記(二):Spring Boot 運行原理
Spring Boot學習筆記(三):Spring Boot Web開發(fā)
Spring Boot學習筆記(四):Spring Boot 數(shù)據(jù)訪問
Spring Boot學習筆記(五):Spring Boot 企業(yè)級開發(fā)
Spring Boot學習筆記(六):Spring Boot 應用監(jiān)控

常見端點介紹

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

序號 端點名 描述 默認開啟(Web) 默認開啟(JMX)
1 actuator 所有端點的列表,需加入spring HATEOAS支持
2 auditevents 顯示應用暴露的審計事件 (比如認證進入、訂單失敗)
3 info 顯示應用的基本信息
4 health 顯示應用的健康狀態(tài)
5 metrics 顯示應用多樣的度量信息
6 loggers 顯示和修改配置的loggers
7 logfile 返回log file中的內(nèi)容(如果logging.file或者logging.path被設置) 不適用
8 httptrace 顯示HTTP足跡,最近100個HTTP request/repsponse
9 env 顯示當前的環(huán)境特性
10 flyway 顯示數(shù)據(jù)庫遷移路徑的詳細信息
11 shutdown 讓你逐步關(guān)閉應用
12 mappings 顯示所有的@RequestMapping路徑
13 scheduledtasks 顯示應用中的調(diào)度任務
14 threaddump 執(zhí)行一個線程dump 不適用
15 heapdump 返回一個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=

查看端點

創(chuàng)建 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對應用進行管理和監(jiān)控。在控制臺輸入 jconsole即可進入JMX。

然后選擇我們的程序進入界面,然后在MBean標簽的org.springframework.boot域下可以對程序進行監(jiān)控和管理。

jmx界面.png

自定義端點

自定義端點需要使用如下注釋。

  • @Endpoint 是構(gòu)建 rest 的唯一路徑。不同請求的操作,調(diào)用時缺少必需參數(shù),或者使用無法轉(zhuǎn)換為所需類型的參數(shù),則不會調(diào)用操作方法,響應狀態(tài)將為400(錯誤請求)
  • @ReadOperation = GET 響應狀態(tài)為 200 如果沒有返回值響應 404(資源未找到)。
  • @WriteOperation = POST 響應狀態(tài)為 200 如果沒有返回值響應 204(無響應內(nèi)容)
  • @DeleteOperation = DELETE 響應狀態(tài)為 200 如果沒有返回值響應 204(無響應內(nèi)容)

依舊使用上面的工程,添加一個實體類。

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沒有值。

自定義端點狀態(tài)1.png

再打開一個窗口,輸入 http://localhost:8080/change?status=123 , 這時候再打開 http://localhost:8080/actuator/status ,就可以看到了。

自定義端點狀態(tài)2.png

自定義 HealthIndicator

Health 信息是從 AppliciationContext 中所有的 HealthIndicator 的 Bean 中收集的, Spring 內(nèi)置的HealthIndicator 如下所示。

名稱 描述
CassandraHealthIndicator 檢查 Cassandra 數(shù)據(jù)庫是否啟動。
DiskSpaceHealthIndicator 檢查磁盤空間不足。
DataSourceHealthIndicator 檢查是否可以獲得連接 DataSource。
ElasticsearchHealthIndicator 檢查 Elasticsearch 集群是否啟動。
InfluxDbHealthIndicator 檢查 InfluxDB 服務器是否啟動。
JmsHealthIndicator 檢查 JMS 代理是否啟動。
MailHealthIndicator 檢查郵件服務器是否啟動。
MongoHealthIndicator 檢查 Mongo 數(shù)據(jù)庫是否啟動。
Neo4jHealthIndicator 檢查 Neo4j 服務器是否啟動。
RabbitHealthIndicator 檢查 Rabbit 服務器是否啟動。
RedisHealthIndicator 檢查 Redis 服務器是否啟動。
SolrHealthIndicator 檢查 Solr 服務器是否已啟動。

要實現(xiàn)自己的 HealthIndicator 只需要實現(xiàn) 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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容