SpringBoot - 監控工具 Actuator

By 古古 2020/07/14 Spring Boot

Actuator 是 SpringBoot 提供的監控功能,可以用來查看當前的 SpringBoot 程式運行的內部狀況,譬如知道自動化配置的資訊、創建的 Spring beans 和獲取當前的 properties 屬性值

需要注意的是,SpringBoot 1.x 和 2.x 的 Actuator 監控設定差超多,不僅提供的 endpoint 路徑不一樣,連 application.properties 的配置也不一樣,此處介紹的為 SpringBoot 2.2.8 版本

使用 SpringBoot Actuator

如果要使用 SpringBoot Actuator 提供的監控功能,需要先加入相關的 maven dependency

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

只要加上了這個 maven dependency,SpringBoot 在運行時就會自動開啟 /actuator/health/actuator/info 這兩個 endpoint,我們就可以透過這兩個 endpoint 查看當前 SpringBoot 運行的情況

Actuator 其實還提供更多樣化的 endpoint 讓我們監控 SpringBoot Application,但是因為安全因素,所以需要另外設置才能打開這些 endpoint,詳細的設置方式下面解說

Actuator 提供的所有 endpoint

此處使用的是 SpringBoot 2.2.8 版本, Spring 官方文件

HTTP方法 Endpoint 描述
GET /actuator 查看有哪些 Actuator endpoint 是開放的
GET /actuator/auditevent 查看 audit 的事件,例如認證進入、訂單失敗,需要搭配 Spring security 使用, sample code
GET /actuator/beans 查看運行當下裡面全部的 bean,以及他們的關係
GET /actuator/conditions 查看自動配置的結果,記錄哪些自動配置條件通過了,哪些沒通過
GET /actuator/configprops 查看注入帶有 @ConfigurationProperties 類的 properties 值為何(包含默認值)
GET /actuator/env (常用) 查看全部環境屬性,可以看到 SpringBoot 載入了哪些 properties,以及這些 properties 的值(但是會自動*掉帶有 key、password、secret 等關鍵字的 properties 的值,保護安全資訊,超聰明!)
GET /actuator/flyway 查看 flyway DB 的 migration 資訊
GET /actuator/health (常用) 查看當前 SpringBoot 運行的健康指標,值由 HealthIndicator 的實現類提供(所以可以自定義一些健康指標資訊,加到這裡面)
GET /actuator/heapdump 取得 JVM 當下的 heap dump,會下載一個檔案
GET /actuator/info 查看 properties 中 info 開頭的屬性的值,沒啥用
GET /actuator/mappings 查看全部的 endpoint(包含 Actuator 的),以及他們和 Controller 的關係
GET /actuator/metrics 查看有哪些指標可以看(ex: jvm.memory.max、system.cpu.usage),要再使用/actuator/metrics/{metric.name}分別查看各指標的詳細資訊
GET /actuator/scheduledtasks 查看定時任務的資訊
POST /actuator/shutdown 唯一一個需要 POST 請求的 endpoint,關閉這個 SpringBoot 程式

開啟受保護的 endpoint 的方法

因為安全的因素,所以 Actuator 默認只會開放 /actuator/health/actuator/info 這兩個 endpoint,如果要開放其他 endpoint 的話,需要額外在 application.properties 中做設置

# 可以這樣寫,就會開啟所有endpoints(不包含shutdown)
management.endpoints.web.exposure.include=*

# 也可以這樣寫,就只會開啟指定的endpoint,因此此處只會再額外開啟/actuator/beans和/actuator/mappings
management.endpoints.web.exposure.include=beans,mappings

# exclude可以用來關閉某些endpoints
# exclude通常會跟include一起用,就是先include了全部,然後再exclude /actuator/beans這個endpoint
management.endpoints.web.exposure.exclude=beans
management.endpoints.web.exposure.include=*

# 如果要開啟/actuator/shutdown,要額外再加這一行
management.endpoint.shutdown.enabled=true

除此之外,也可以改變 /actuator 的路徑,可以自定義成自己想要的路徑

#這樣寫的話,原本內建的/actuator/xxx路徑,都會變成/manage/xxx,可以用來防止被其他人猜到
management.endpoints.web.base-path=/manage

溫馨提醒

如果開啟了 Actuator 默認不打開的 endpoints,建議一定要加上 Spring security 之類的做 endpoint 保護,避免重要資訊外洩

Spring security 保護 Actuator 的方式和一般的 endpoint 一樣,就把 /actuator/xxx 當作正常的 endpoint 來設置就可以了