在企業級應用中,學習瞭如何進行SpringBoot應用的功能開發,以及如何寫單元測試、集成測試等仍是不夠的。在實際的軟件開發中還須要:應用程序的監控和管理。SpringBoot的Actuator模塊實現了應用的監控與管理。java
生產系統中,每每須要對系統實際運行的狀況(例如cpu、io、disk、db、業務功能等指標)進行監控運維。在SpringBoot項目中Actuator模塊提供了衆多HTTP接口端點(Endpoint),來提供應用程序運行時的內部狀態信息。web
Actuator模塊提供了一個監控和管理生產環境的模塊,可使用http、jmx、ssh、telnet等來管理和監控應用。包括應用的審計(Auditing)、健康(health)狀態信息、數據採集(metrics gathering)統計等監控運維的功能。同時,提供了能夠擴展 Actuator端點(Endpoint)自定義監控指標。這些指標都是以JSON接口數據的方式呈現。算法
使用Spring Boot Actuator須要加入以下依賴:spring
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>複製代碼
actuator並無默認集成在自動配置中,而在做爲獨立的項目來呈現的。當引入了上面的依賴,默認會引入actuator相關的兩個項目:數據庫
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
</dependency>複製代碼
其中spring-boot-actuator爲功能實現,spring-boot-actuator-autoconfigure爲自動配置。json
須要注意:因SpringBoot Actuator會暴露服務的詳細信息,爲了保障安全性,建議添加安全控制的相關依賴spring-boot-starter-security,這樣在訪問應用監控端點時,都須要輸入驗證信息。所需依賴以下:tomcat
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>複製代碼
關於security的使用咱們在此不進行展開,可在application文件中配置相應的訪問密碼:安全
spring:
security:
user:
name: admin
password: admin複製代碼
在下面的內容中爲了方便,咱們暫時不引入security。服務器
通過以上步驟的操做,啓動SpringBoot項目,actuator便自動集成配置了,可經過:http://localhost:8080/actuator 訪問,結果以下:微信
{
"_links": {
"self": {
"href": "http://localhost:8080/actuator",
"templated": false
},
"health": {
"href": "http://localhost:8080/actuator/health",
"templated": false
},
"health-component": {
"href": "http://localhost:8080/actuator/health/{component}",
"templated": true
},
"health-component-instance": {
"href": "http://localhost:8080/actuator/health/{component}/{instance}",
"templated": true
},
"info": {
"href": "http://localhost:8080/actuator/info",
"templated": false
}
}
}複製代碼
默認支持的連接有:
/actuator
/actuator/health
/health/{component}/{instance}
/health/{component}
/actuator/info複製代碼
能夠在application配置文件中配置開啓更多的監控信息:
management:
endpoints:
web:
exposure:
include: '*'
# base-path: /monitor
endpoint:
health:
show-details: always
shutdown:
enabled: true複製代碼
監控信息若是須要跨越調用,可經過CORS配置來支持,默認處於禁用狀態。設置management.endpoints.web.cors.allowed-origins屬性後開啓。
好比容許來自https://www.choupangxia.com 域的GET和POST調用:
management:
endpoints:
web:
cors:
allowed-origins: https://www.choupangxia.com
allowed-methods: GET,POST複製代碼
Spring Boot Actuator提供了很是豐富的監控接口,能夠經過這些接口瞭解應用程序運行時的內部情況。Actuator也支持用戶自定義添加端點,能夠根據實際應用,定義一些比較關心的指標,在運行期進行監控。
HTTP方法 | 路徑 | 描述 |
---|---|---|
GET | /auditevents | 顯示當前應用程序的審計事件信息 |
GET | /beans | 顯示一個應用中全部Spring Beans的完整列表 |
GET |
/conditions | 顯示配置類和自動配置類(configuration and auto-configuration classes)的狀態及它們被應用或未被應用的緣由。 |
GET |
/configprops |
顯示一個全部@ConfigurationProperties的集合列表 |
GET |
/env |
顯示來自Spring的ConfigurableEnvironment的屬性。 |
GET |
/flyway | 顯示數據庫遷移路徑,若是有的話。 |
GET |
/health |
顯示應用的健康信息(當使用一個未認證鏈接訪問時顯示一個簡單的’status’,使用認證鏈接訪問則顯示所有信息詳情) |
GET |
/info |
顯示任意的應用信息 |
GET |
/liquibase |
展現任何Liquibase數據庫遷移路徑,若是有的話 |
GET |
/metrics |
展現當前應用的metrics信息 |
GET |
/mappings |
顯示一個全部@RequestMapping路徑的集合列表 |
GET |
/scheduledtasks |
顯示應用程序中的計劃任務 |
GET |
/sessions |
容許從Spring會話支持的會話存儲中檢索和刪除(retrieval and deletion)用戶會話。使用Spring Session對反應性Web應用程序的支持時不可用。 |
POST |
/shutdown |
容許應用以優雅的方式關閉(默認狀況下不啓用) |
GET |
/threaddump |
執行一個線程dump |
若是使用web應用(Spring MVC, Spring WebFlux, 或者 Jersey),還可使用如下接口:
HTTP方法 | 路徑 | 描述 |
---|---|---|
GET | /heapdump | 返回一個GZip壓縮的hprof堆dump文件 |
GET | /jolokia | 經過HTTP暴露JMX beans(當Jolokia在類路徑上時,WebFlux不可用) |
GET | /logfile | 返回日誌文件內容(若是設置了logging.file或logging.path屬性的話),支持使用HTTP Range頭接收日誌文件內容的部分信息 |
GET | /prometheus | 以能夠被Prometheus服務器抓取的格式顯示metrics信息 |
health主要用來檢查應用的運行狀態,這是使用頻次最高的監控點。一般使用此接口顯示應用實例的運行狀態,以及應用不「健康」的緣由,好比數據庫鏈接、磁盤空間不夠等。
默認狀況下health的狀態是開放的,訪問:http://localhost:8080/actuator/health 便可看到應用的狀態。
{
"status" : "UP"
}
複製代碼
設置狀態碼順序:setStatusOrder(Status.DOWN,Status.OUTOFSERVICE, Status.UP, Status.UNKNOWN)。過濾掉不能識別的狀態碼。若是無任何狀態碼,整個SpringBoot應用的狀態是UNKNOWN。將全部收集到的狀態碼排序。返回有序狀態碼序列中的第一個狀態碼,做爲整個SpringBoot應用的狀態。
Health經過合併幾個健康指數檢查應用的健康狀況。SpringBoot Actuator會自動配置如下內容:
名稱 | 描述 |
---|---|
CassandraHealthIndicator | 檢查Cassandra數據庫是否已啓動。 |
CouchbaseHealthIndicator | 檢查Couchbase羣集是否已啓動。 |
DiskSpaceHealthIndicator | 檢查磁盤空間不足。 |
DataSourceHealthIndicator | 檢查是否能夠創建鏈接DataSource。 |
ElasticsearchHealthIndicator | 檢查Elasticsearch集羣是否已啓動。 |
InfluxDbHealthIndicator | 檢查InfluxDB服務器是否已啓動。 |
JmsHealthIndicator | 檢查JMS代理是否啓動。 |
MailHealthIndicator | 檢查郵件服務器是否已啓動。 |
MongoHealthIndicator | 檢查Mongo數據庫是否已啓動。 |
Neo4jHealthIndicator | 檢查Neo4j服務器是否已啓動。 |
RabbitHealthIndicator | 檢查Rabbit服務器是否已啓動。 |
RedisHealthIndicator | 檢查Redis服務器是否啓動。 |
SolrHealthIndicator | 檢查Solr服務器是否已啓動。 |
能夠經過設置 management.health.defaults.enabled屬性來所有禁用。
原生端點分爲三大類:
/conditions:該端點用來獲取應用的自動化配置報告,其中包括全部自動化配置的候選項。同時還列出了每一個候選項自動化配置的各個先決條件是否知足。該端點能夠幫助咱們方便的找到一些自動化配置爲何沒有生效的具體緣由。
該報告內容將自動化配置內容分爲兩部分:positiveMatches中返回的是條件匹配成功的自動化配置和negativeMatches中返回的是條件匹配不成功的自動化配置。
部分代碼以下:
"contexts": {
"application": {
"positiveMatches": {
"MsgAutoConfiguration": [
{
"condition": "OnClassCondition",
"message": "@ConditionalOnClass found required class 'com.secbro2.msg.MsgService'"
}
],
"MsgAutoConfiguration#msgService": [
{
"condition": "OnPropertyCondition",
"message": "@ConditionalOnProperty (msg.enabled=true) matched"
},
{
"condition": "OnBeanCondition",
"message": "@ConditionalOnMissingBean (types: com.secbro2.msg.MsgService; SearchStrategy: all) did not find any beans"
}
],複製代碼
/info:就是在配置文件中配置的以info開頭的信息,如配置爲:
info:
app:
name: spring-boot-actuator
version: 1.0.0複製代碼
返回結果:
{
"app":{
"name":"spring-boot-actuator",
"version":"1.0.0"
}
}複製代碼
info中配置的參數也能夠經過符號*@*包圍的屬性值來自pom.xml文件中的元素節點。以下:
info:
build:
artifact: @project.artifactId@
name: @project.name@
description: @project.description@
ersion: @project.version@複製代碼
返回結果:
{
"build": {
"artifact": "spring-learn",
"name": "spring-learn",
"description": "Demo project for Spring Boot",
"ersion": "0.0.1-SNAPSHOT"
}
}複製代碼
/beans:該端點用來獲取應用上下文中建立的全部Bean。
{
"contexts": {
"application": {
"beans": {
"endpointCachingOperationInvokerAdvisor": {
"aliases": [],
"scope": "singleton",
"type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
"resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
"dependencies": ["environment"]
},
"defaultServletHandlerMapping": {
"aliases": [],
"scope": "singleton",
"type": "org.springframework.web.servlet.HandlerMapping",
"resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]",
"dependencies": []
},
},
"parentId": null
}
}
}複製代碼
接口展示了bean的別名、類型、是否單例、類的地址、依賴等信息。
/configprops:該端點用來獲取應用中配置的屬性信息報告。
{
"spring.transaction-org.springframework.boot.autoconfigure.transaction.TransactionProperties": {
"prefix": "spring.transaction",
"properties": {}
}
}複製代碼
上面展現了TransactionProperties屬性的配置信息。
/mappings:該端點用來返回全部SpringMVC的控制器映射關係報告。
{
"handler": "Actuator web endpoint 'beans'",
"predicate": "{GET /actuator/beans, produces [application/vnd.spring-boot.actuator.v2+json || application/json]}",
"details": {
"handlerMethod": {
"className": "org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler",
"name": "handle",
"descriptor": "(Ljavax/servlet/http/HttpServletRequest;Ljava/util/Map;)Ljava/lang/Object;"
},
"requestMappingConditions": {
"consumes": [],
"headers": [],
"methods": ["GET"],
"params": [],
"patterns": ["/actuator/beans"],
"produces": [{
"mediaType": "application/vnd.spring-boot.actuator.v2+json",
"negated": false
}, {
"mediaType": "application/json",
"negated": false
}]
}
}
}複製代碼
/env:該端點與/configprops不一樣,它用來獲取應用全部可用的環境屬性報告。包括:環境變量、JVM屬性、應用的配置配置、命令行中的參數。
應用配置類提供的指標爲靜態報告,而度量指標類端點提供的報告內容則是動態變化的,提供了應用程序在運行過程當中的一些快照信息,好比:內存使用狀況、HTTP請求統計、外部資源指標等。這些端點對於構建微服務架構中的監控系統很是有幫助。
/metrics:該端點用來返回當前應用的各種重要度量指標,好比:內存信息、線程信息、垃圾回收信息等。
{
"names": [
"jvm.memory.max",
"jvm.threads.states",
"http.server.requests",
"process.files.max",
"jvm.gc.memory.promoted",
"system.load.average.1m",
"jvm.memory.used",
"jvm.gc.max.data.size",
"jvm.gc.pause",
"jvm.memory.committed",
"system.cpu.count",
"logback.events",
"tomcat.global.sent",
"jvm.buffer.memory.used",
"tomcat.sessions.created",
"jvm.threads.daemon",
"system.cpu.usage",
"jvm.gc.memory.allocated",
"tomcat.global.request.max",
"tomcat.global.request",
"tomcat.sessions.expired",
"jvm.threads.live",
"jvm.threads.peak",
"tomcat.global.received",
"process.uptime",
"tomcat.sessions.rejected",
"process.cpu.usage",
"tomcat.threads.config.max",
"jvm.classes.loaded",
"jvm.classes.unloaded",
"tomcat.global.error",
"tomcat.sessions.active.current",
"tomcat.sessions.alive.max",
"jvm.gc.live.data.size",
"tomcat.threads.current",
"process.files.open",
"jvm.buffer.count",
"jvm.buffer.total.capacity",
"tomcat.sessions.active.max",
"tomcat.threads.busy",
"process.start.time"
]
}複製代碼
從上面的示例中有這些重要的度量值:
/threaddump:會生成當前線程活動的快照。方便咱們在平常定位問題的時候查看線程的狀況。主要展現了線程名、線程ID、線程的狀態、是否等待鎖資源等信息。
{
"threads": [{
"threadName": "Reference Handler",
"threadId": 2,
"blockedTime": -1,
"blockedCount": 2,
"waitedTime": -1,
"waitedCount": 0,
"lockName": null,
"lockOwnerId": -1,
"lockOwnerName": null,
"daemon": true,
"inNative": false,
"suspended": false,
"threadState": "RUNNABLE",
"priority": 10,
"stackTrace": [{
"classLoaderName": null,
"moduleName": "java.base",
"moduleVersion": "11.0.4",
"methodName": "waitForReferencePendingList",
"fileName": "Reference.java",
"lineNumber": -2,
"className": "java.lang.ref.Reference",
"nativeMethod": true
}
...
"lockedMonitors": [],
"lockedSynchronizers": [{
"className": "java.util.concurrent.locks.ReentrantLock$NonfairSync",
"identityHashCode": 2060076420
}],
"lockInfo": null
...
{
"threadName": "DestroyJavaVM",
"threadId": 42,
"blockedTime": -1,
"blockedCount": 0,
"waitedTime": -1,
"waitedCount": 0,
"lockName": null,
"lockOwnerId": -1,
"lockOwnerName": null,
"daemon": false,
"inNative": false,
"suspended": false,
"threadState": "RUNNABLE",
"priority": 5,
"stackTrace": [],
"lockedMonitors": [],
"lockedSynchronizers": [],
"lockInfo": null
}]
}複製代碼
/trace:該端點用來返回基本的HTTP跟蹤信息。默認狀況下,跟蹤信息的存儲採用。
/shutdown:配置文件中配置開啓此功能:
management.endpoint.shutdown.enabled=true複製代碼
使用 curl 模擬 post 請求此接口:
curl -X POST "http://localhost:8080/actuator/shutdown"複製代碼
顯示結果爲:
{
"message": "Shutting down, bye..."
}複製代碼
本篇文章介紹了SpringBoot Actuator監控的基本功能和詳解,下篇文章將會帶你們瞭解一下該功能在Spring Boot中的實現原理。歡迎關注公衆號「程序新視界」。
原文連接:《Spring Boot Actuator監控使用詳解》