Spring Boot 2 Actuator監控系統
本文介紹Spring Boot2 Actuator,首先介紹基礎概念,接着學習如何使用、配置、擴充這個監控工具。
1. 什麼是 Actuator
Actuator提供産品級的功能特性,使得監控應用、收集名額和流量、資料庫狀态變得非常簡單。該庫的主要優勢是能夠獲得産品級工具,無需自己實際實作。主要用于暴露正在運作系統的操作資訊,包括健康狀态、名額資訊、系統及環境資訊等。可以使用HTTP或JMX方式進行通信互動。
隻要加入依賴,預設提供幾個健康端點可用,對于大多數Spring子產品,有多種方式很容易進行配置或擴充。
要啟用Actuator,僅需加入下面依賴包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
注:無論Spring boot版本是什麼,這都是有效的。但本文主要聚焦2.x版本。
2. Spring Boot2 Actuator
2.x版本Actouator在之前的基礎上,簡化模型,擴充其功能并加入更好的預設能力。 首先該版本與技術無關,與系統合并安全功能簡化模型。最後,在各種變化中,重要的是要記住,其中一些是破壞的。這包括HTTP請求和響應以及Java api。
此外,最新版本現在支援CRUD模型,而不是舊的讀/寫模型。
2.1 技術支援
目前主要版本與底層技術無關,而1.x版本依賴MVC,即Servlet API。2.x版本定義自己的模型,可插拔、可擴充,無需依賴MVC。是以使用新的模型,既可以使用MVC,也可以使用WebFlux作為底層web技術。而且還可以實作适配層支援未來技術。最後要說的是,仍然支援JMX暴露的端點,且無需額外代碼。
2.2 重要變化
與之前版本不同的是,廢棄了大多數Actuator端點,僅保留兩個預設的端點:/health 和 /info 。
如果想啟用所有端點,可以設定
management.endpoints.web.exposure.include=*.
,當然也可以列出僅啟用部分的端點清單。
Actuator 現在與正常應用共享安全規則配置,是以其安全模型也非常簡單。調整Actuator安全規則,僅增加
/actuator/**
:
@Bean
public SecurityWebFilterChain securityWebFilterChain(
ServerHttpSecurity http) {
return http.authorizeExchange()
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated()
.and().build();
}
另外,Actuator的預設端點是在
/actuator
路徑下。和前面版本一樣,可以調整該路徑,使用新的屬性:
management.endpoints.web.base-path
。
2.3 預定義的端點
下面看看常用端點,大多數之前版本都有。但還是有變動,增加、删除和重構了一些端點。
端點 | 描述 |
---|---|
/auditevents | 列出所有安全審計相關的事件,如使用者登入、登出。同時也可以根據使用者的字段進行過濾。 |
/beans | 傳回所有BeanFactory中有效bean,與/auditevents不同,其不支援過濾。 |
/conditions | 之前是/autoconfig,傳回自動配置中條件配置資訊 |
/configprops | 傳回所有@ConfigurationProperties配置bean清單 |
/env | 列出目前環境屬性,另外也可以傳回單個屬性資訊 |
/flyway | 提供Flyway 資料庫遷移資訊 |
/health | 傳回應用的健康名額資訊 |
/heapdump | 傳回應用使用的JVM中堆記憶體快照 |
/info | 傳回通用資訊,包括自定義屬性資訊 |
/liquibase | 提供Liquibase資料庫遷移資訊 |
/logfile | 傳回應用日志 |
/loggers | 可以查詢或修改應用日志級别 |
/metrics | 應用的度量名額資訊,包括通用及自定義的度量名額 |
/prometheus | 和上面端點一樣,傳回所有度量名額資訊,但相容Prometheus server(開源監控系統)格式 |
/scheduledtasks | 傳回應用中所有的排程任務細節 |
/sessions | 列出 HTTP sessions,如果我們使用Spring Session |
/shutdown | 執行應用程式優雅退出動作 |
/threaddump | 傳回底層JVM線程資訊快照 |
2.4 Actuator 總入口點
Spring Boot 增加了一個總入口點可以獲得所有有效actuator,利用總入口點可以獲得Actuator入口及其相應url。
預設總入口點通路位址為
/actuator
,如果發送GET請求,傳回所有不同的Actuator:
如果你自定義管理基礎路徑,那麼應該使用你定義的路徑作為url。舉例,如果你設定
management.endpoints.web.base-path=/mgmt
,那麼應該發送 /mgmt入口點請求。有趣的是,當設定基礎路徑為
/
時則禁用Actuator入口點,這是為了防止和其他映射沖突。
2.5 健康名額
和之前版本一樣,可以很容易增加自定義名額。與其他API不同,建立自定義健康入口點的抽象沒變,但增加了新的接口
ReactiveHealthIndicator
實作響應式健康檢查。
下面看一個響應式健康檢查示例:
@Component
public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator {
@Override
public Mono<Health> health() {
return checkDownstreamServiceHealth().onErrorResume(
ex -> Mono.just(new Health.Builder().down(ex).build())
);
}
private Mono<Health> checkDownstreamServiceHealth() {
// we could use WebClient to check health reactively
return Mono.just(new Health.Builder().up().build());
}
}
健康名額有一個很友善特性是可以聚集作為層次結構的一部分。是以對于前面的示例,可以将所有下流服務作為子分類,該分類可以作為嵌入服務。這塊内容後續文章會更詳細講解。
2.6 健康名額分組
Spring Boot2.2 可以組織多個健康名額為組,對組成員使用相同名額進行配置。舉例,建立分組
costom
分組,application.properties配置如下:
management.endpoint.health.group.custom.include=diskSpace,ping
上面配置定義了
custom
組,包括diskSpace,ping健康名額。現在如果通路
/actuator/health
端點,響應中包括了我們增加的分組:
{"status":"UP","groups":["custom"]}
使用健康分組,可以看到多個健康名額的組合結果。在這種情況,如果發送
/actuator/health/custom
請求:
{"status":"UP"}
現在可以增加配置顯示分組内名額的詳細資訊:
management.endpoint.health.group.custom.show-components=always
management.endpoint.health.group.custom.show-details=always
現在通路
/actuator/health/custom
端點,傳回内容包括:
{
"status": "UP",
"components": {
"diskSpace": {
"status": "UP",
"details": {
"total": 214748360704,
"free": 112445571072,
"threshold": 10485760,
"exists": true
}
},
"ping": {
"status": "UP"
}
}
}
也可以設定為僅針對授權使用者才展示詳細資訊:
management.endpoint.health.group.custom.show-components=when_authorized
management.endpoint.health.group.custom.show-details=when_authorized
我們還增加自定義狀态映射。舉例,代替200響應碼傳回207狀态碼:
management.endpoint.health.group.custom.status.http-mapping.up=207
該配置告訴Spring Boot,如果custom分組狀态是UP則傳回207狀态碼。
2.7 Spring Boot 2度量名額
Spring Boot2.0開始使用Micrometer實作内置度量,我們期望有較大改變。如果應用程式使用度量服務,則GaugeService或CounterService它們将不再可用。而是可以和Micrometer直接進行互動,Spring Boot2.0自動配置了MeterRegistry Bean。
另外,Micrometer現在是Actuator依賴的一部分,是以無需增加額外的依賴。通路
/metrics
可以看到新的響應内容:
{
"names": [
"hikaricp.connections",
"hikaricp.connections.acquire",
"hikaricp.connections.active",
"hikaricp.connections.creation",
"hikaricp.connections.idle",
"hikaricp.connections.max",
"hikaricp.connections.min",
"hikaricp.connections.pending",
"hikaricp.connections.timeout",
"hikaricp.connections.usage",
"jdbc.connections.active",
"jdbc.connections.idle",
"jdbc.connections.max",
"jdbc.connections.min",
"jvm.buffer.count",
"jvm.buffer.memory.used",
"jvm.buffer.total.capacity",
"jvm.classes.loaded",
"jvm.classes.unloaded",
"jvm.gc.live.data.size",
"jvm.gc.max.data.size",
"jvm.gc.memory.allocated",
"jvm.gc.memory.promoted",
"jvm.gc.pause",
"jvm.memory.committed",
"jvm.memory.max",
"jvm.memory.used",
"jvm.threads.daemon",
"jvm.threads.live",
"jvm.threads.peak",
"jvm.threads.states",
"logback.events",
"process.cpu.usage",
"process.start.time",
"process.uptime",
"system.cpu.count",
"system.cpu.usage",
// ...
]
}
如果需要檢視特定度量的實際值,可以浏覽對應度量名額,如:/actuator/metrics/jvm.gc.pause :
{
"name": "jvm.gc.pause",
"description": "Time spent in GC pause",
"baseUnit": "seconds",
"measurements": [
{
"statistic": "COUNT",
"value": 2
},
{
"statistic": "TOTAL_TIME",
"value": 0.172
},
{
"statistic": "MAX",
"value": 0
}
],
"availableTags": [
{
"tag": "cause",
"values": [
"G1 Evacuation Pause",
"Metadata GC Threshold"
]
},
{
"tag": "action",
"values": [
"end of minor GC"
]
}
]
}
如我們所看到的,顯示的度量更加全面了。不僅包括不同的值,還包括一些相關的中繼資料。
2.8 建立自定義端點
前面提到可以建立自定義端點。Spring Boot2重新設計了該實作,支援技術無關模型。下面我們建立一個Actuator端點,用于查詢、啟用、禁用應用中的特征标志。
@Component
@Endpoint(id = "features")
public class FeaturesEndpoint {
private Map<String, Feature> features = new ConcurrentHashMap<>();
public FeaturesEndpoint(){
features.put("name", Feature.of(true)); // 增加示例内容
}
@ReadOperation
public Map<String, Feature> features() {
return features;
}
@ReadOperation
public Feature feature(@Selector String name) {
return features.get(name);
}
@WriteOperation
public void configureFeature(@Selector String name, Feature feature) {
features.put(name, feature);
}
@DeleteOperation
public void deleteFeature(@Selector String name) {
features.remove(name);
}
public static class Feature implements Serializable {
private Boolean enabled;
public Feature(Boolean enabled) {
this.enabled = enabled;
}
public static Feature of(Boolean flag){
return new Feature(true);
}
public Boolean getEnabled(){
return enabled;
}
}
}
定義端點需要定義bean,在上面的示例中我們在bean上使用@Component、@Endpoint兩個注解。@Endpoint注解中的參數定義請求路由
/actuator/features
。定義好bean後,開始定義操作:
- @ReadOperation – 映射 HTTP GET
- @WriteOperation – 映射 HTTP POST
- @DeleteOperation – 映射 HTTP DELETE
當我們啟動應用時,Spring Boot會自動注冊該bean。這裡需要指出的是:
- 定義端點并不依賴MVC,不再需要實作特定接口(1.x版本需要)
- 可以通過@Endpoint注解第二個參數啟用或禁用帶端點;如:@Endpoint(id = “features”, enableByDefault = false)
- 可以使用@DeleteOperation注解定義DELETE操作
我們可以通過
/actuator/features
、
/actuator/features/{name}
進行驗證結果。
2.9 啟用所有端點
為了使用http方式通路Actuator端點,需要啟用并暴露它們。預設情況下除了
/shutdown
端點都啟用,但僅 /health 和 /info 兩個端點預設被暴露。增加下面配置可以暴露所有端點:
management.endpoints.web.exposure.include=*
顯示啟用特定端點:
management.endpoint.shutdown.enabled=true
暴露所有啟用端點除了某個:
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=loggers
3. 總結
本文詳細介紹了Spring Boot2 Actuator,包括2.x版本新的變化、常用配置以及如何自定義擴充名額。