第11章 Spring Boot Actuator與應(yīng)用監(jiān)控
Spring Boot的Actuator 將應(yīng)用的很多信息暴露出來,如容器中的 bean,自動(dòng)配置時(shí)的決策,運(yùn)行時(shí)健康狀態(tài), metrics等等。Actuator提供了三中方式獲取這些信息:
HTTP Endpoints
Remote Shell
JMX (MBeans) 當(dāng)然通過繼承指定的類來自定義一些 actuator信息,暴露自己想要的信息。
11.1 使用Spring Boot Actuator監(jiān)控應(yīng)用
1.Spring boot Actuator Endpoints介紹
Actuator是Spring Boot提供的附加特性,來幫我們監(jiān)控和管理生產(chǎn)環(huán)境下運(yùn)行時(shí)的應(yīng)用程序。我們可以通過HTTP endpoints、JMX或者SSH來監(jiān)控和管理應(yīng)用的健康狀況、系統(tǒng)指標(biāo)、參數(shù)信息、內(nèi)存狀況等等。
Spring Boot Actuator所提供的HTTP監(jiān)控服務(wù)如下表:

上面的這些HTTP服務(wù),我們就叫Endpoint。Endpoint允許對應(yīng)用進(jìn)行上述健康狀況、系統(tǒng)指標(biāo)、參數(shù)信息、內(nèi)存狀況等指標(biāo)的監(jiān)控和交互。Spring Boot提供了很多內(nèi)置的Endpoint,同時(shí)支持定制Endpoint。
Endpoint被暴露的方式取決于采用的技術(shù)(HTTP、JMX、SSH等),大部分應(yīng)用采用HTTP的方式, 暴露的方式即通過Endpoint的ID映射成一個(gè)URL,例如 id=health 的內(nèi)置Endpoint映射到URL=/health, 提供應(yīng)用基礎(chǔ)健康檢查信息, 為了安全起見,一般不暴露在應(yīng)用服務(wù)端口上,而是暴露在專門的管理端口上。
其中,重點(diǎn)挑兩個(gè)講一下。
/health 提供應(yīng)用程序的健康狀態(tài),或者是某個(gè)核心模塊的健康狀態(tài)。例如,
數(shù)據(jù)庫連接,磁盤使用情況等指標(biāo)。
/metrics,這個(gè)endpoint顯示Metrics 子系統(tǒng)管理的信息。主要是一些度量的值,比如系統(tǒng)的吞吐量,堆棧信息,耗時(shí)(timer),接口被觸發(fā)的次數(shù)(meter,count),對象大?。╣auge)等。metrics的監(jiān)控主要分以下幾種類型:
2.開啟Actuator
很簡單,只需要引入官方提供的starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3.定制Endpoint
Endpoint可以通過application.properties配置文件中的配置項(xiàng)進(jìn)行定制, 格式如下:
endpoints.[name].[property]
有三個(gè)通用的property:
id: id
enable: 開關(guān)
sensitive: 是否需要權(quán)限控制才可以看到
以health為例,/health暴露的監(jiān)控信息是所有實(shí)現(xiàn)了HealthIndicator接口的Bean。
通過自定義HealthIndicator實(shí)現(xiàn)定制health endpoint
@Component
public class HealthCheck implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
public int check() {
// Your logic to check health
return 0;
}
}
輸出類似如下格式:
{
"status" : "DOWN",
"myHealthCheck" : {
"status" : "DOWN",
"Error Code" : 1,
"Description" : "You custom MyHealthCheck endpoint is down"
},
"diskSpace" : {
"status" : "UP",
"free" : 209047318528,
"threshold" : 10485760
}
}
4.創(chuàng)建新的Endpoint
一般通過繼承AbstractEndpoint<T>抽象類創(chuàng)建一個(gè)新的Endpoint, 或者直接實(shí)現(xiàn)Endpoint<T>接口,AbstractEndpoint<T>抽象類也實(shí)現(xiàn)了Endpoint<T>接口。
@Component
public class CustomEndpoint implements Endpoint<List<String>> {
public String getId() {
return "customEndpoint";
}
public boolean isEnabled() {
return true;
}
public boolean isSensitive() {
return true;
}
public List<String> invoke() {
// Custom logic to build the output
List<String> messages = new ArrayList<String>();
messages.add("This is message 1");
messages.add("This is message 2");
return messages;
}
}
id=customEndpoint, 對應(yīng)的URL為/customEndpoint
輸出信息格式如下:
[ "This is message 1", "This is message 2" ]