SpringBoot Actuator 健康監測
一、簡介
actuator是springboot中的一個附加功能,官方是對它這樣介紹的:
Spring Boot包含了許多附加功能,幫助您在將應用程序推送到生產環境時監視和管理它。您可以選擇使用HTTP端點或與JMX一起管理和監視應用程序。
審核(Auditing)、運行狀況(health)和度量收集(metrics gathering)也可以自動應用於您的應用程序。
二、簡單使用
2.1、首先在springboot工程中引入依賴
<!-- 健康監測 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.2、啟動springboot項目
可以看到,默認暴露了兩個endpoint,其實就是 health 和 info
打開地址:http://localhost:8080/actuator/info 或者 http://localhost:8080/actuator/health
2.3、application.yml自定義配置
這里配置了暴露所有endpoint,並配置訪問路徑(如 health):ip:8081/health
server:
port: 8080
management: # actuator
server:
port: 8081 # actuator access port
endpoints:
web:
base-path: / # root path
exposure:
include: "*" # include all endpoint
三、自定義Endpoint
3.1、如上所示,首先引入健康監測依賴
3.2、編寫自定義的Endpoint
@Configuration
@Endpoint(id = "demo-endpoint")
public class DemoEndpoint {
@ReadOperation(produces = "application/json")
public Map<String, Object> operation(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("demo", "{demo: endpoint test}");
return map;
}
}
3.3、配置
management.endpoints.web.exposure.include=demo-endpoint
或
management.endpoints.web.exposure.include="*"
注意
a、@EndPoint中的id不能使用駝峰法,需要以-分割
b、Spring Boot會去掃描@Endpoint注解下的@ReadOperation, @WriteOperation, @DeleteOperation注解,分別對應生成Get/Post/Delete的Mapping。
注解中有個produces參數,可以指定media type, 如:application/json等。