Spring boot 之 actuator

spring-boot-starter-actuator是Spring-boot中非常有用的模塊,該模塊能夠自動爲Spring boot構建的應用提領一系列用於監控的端點。同時,也爲後續的Spring-cloud在實現各個微服務組件的時候,進行了很多擴展。spring-boot-starter-actuator對實施中小的微服務的團隊有效的省去或大大減少監控系統在採集應用指標時的開發量。當然有些時候也需要我們自己對其做一些簡單的擴展。

下面我們通過一個簡單入門的Spring-boot項目來講解一下spring-boot-starter-actuator模塊功能。

打開IDEA新建一個Spring-boot項目,在pom.xml文件中加入以下依賴:

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

增加該依賴以後,我們啓動項目,會發現以下內容:


默認在2.0.3版本下,Spring-boot啓動了health和info端點。

要想啓動自己想要的監控端點或者全部的端點,需要application.properties配置文件中,添加:

management.endpoints.web.exposure.include

如果要啓動全部的端點,那麼就配置:

management.endpoints.web.exposure.include=*

如果只想啓動指定的端點,就配置:

management.endpoints.web.exposure.include=["health","info","loggers","env","beans"]

然後啓動項目,通過瀏覽器訪問 /actuator端點就可以看到啓動了那些監控端點:


在spring-boot-starter-actuator模塊中默認的原生端點包括三類:

1、應用配置類;2、度量指標類;3、操作控制類。

接下來對上面三類中幾個比較常用的端點進行講解:

應用配置類中:

(1)/beans 端點,通過/actuator/beans來訪問,用來獲取上下文中創建的所有bean:


通過上圖我們可以看到bean中包含了下面這些信息:

bean:Bean的名稱

scope: bean的作用域

type:Bean的java類型

resource:class文件的具體路徑

dependencies:依賴的bean名稱 ;

(2)/configprops ,訪問路徑:/actuator/configprops,該端點用來獲取應用中配置的屬性信息報告。


prefix屬性代表了屬性的配置前綴,properties代表了各個屬性的名稱和值,如果我們要關閉這個端點,就可以在配置文件中配置:

management.endpoint.configprops.enabled=false

(3)/env ,訪問路徑:/actuator/env ,是用來獲取應用所有可用的環境屬性報告,包括環境變量、JVM屬性、應用的配置、命令行的參數.


上圖中就顯示了部分環境屬性,我們可以使用@ConfigurationProperties註解將它們引入到我們程序中來使用,爲了安全考慮,對於一些password,secret,key這些關鍵詞,進行了隱藏。

(4)/mappings,訪問路徑 /actuator/mappings,該端點用來返回所有的SpringMVC的控制器映射關係報告。


(5) /info  訪問路徑:/actuator/info,用來返回一些在配置文件自定義的屬性,如果沒有自定義的屬性,默認會返回一個空的json字符串,但是如果在application.properties配置文件中用info前綴了設置一些屬性,比如:

info.app.name=spring-boot-hello
info.app.version=0.0.1

然後再訪問info端點:

{"app":{"name":"spring-boot-hello","version":"0.0.1"}}


亮度指標類:提供的報告內容則是動態變化的,這些端點提供了應用程序在運行過程中的一些快照信息,比如內存使用情況,HTTP請求統計,外部資源指標等。

(1)/metrics  訪問路徑/actuator/metrics  ,這個端點用來統計內存信息、線程信息、垃圾回收信息等.


然後可以通過上面的值來獲得每一個指標的值,比如:

http://localhost:8888/actuator/metrics/jvm.memory.used

可以得到以下值:


依次類推也可以得到其他的指標值。

(2)/health 訪問路徑:/actuator/health  用來獲取應用的各類健康指標信息。在Spring-boot-starter-actuator模塊中自帶了一些常用的健康指標檢測器。這些檢測器都通過HealthIndicator接口實現,會根據依賴關係的引入自動化裝配,比如下面這些:

檢測器功能
DiskSpaceHealthIndicator低磁盤空間檢測
DataSourceHealthIndicator檢測DataSource的連接是否可用
MongoHealthIndicator檢測Mongo數據庫是否可用
RabbitHealthIndicator檢測Rabbit數據庫是否可用
RedisHealthIndicator檢測Redis數據庫是否可用
SolrHealthIndicator檢測Solr服務器是否可用

如果我們想使用去檢測其他的服務器或者中間體,我們可以自己編寫檢測邏輯,只需要實現HealthIndicator接口,通過重寫health()方法來實現健康檢測。在返回的Health對象中,共有兩個內容,一個是狀態信息,UP 、DOWN、UNKNOWN和OUT_OF_SERVICE;還有一個詳細信息採用Map的方式存儲,通過withDetail函數。如下:

@Component
public class MyHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        int code=check();
        if(code==-1){
            return Health.down().withDetail("Error Code",code).build();
        }
        return Health.up().build();
    }

    private int check(){
      //對監控對象的檢測操作
    }
}


我們也可以自定義狀態碼,在applicatio n.properites文件中,配置health的自定義狀態碼:

management.health.status.order=DOWN,OUT_OF_SERVICE,UNKNOWN,UP,ODD,EVENT
@Component
public class MyHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        if(check()){
            return Health.status("DOWN").withDetail("出錯啦",101).build();
        }
        return Health.status("EVENT").build();
    }

    private boolean check(){
       int num=(int)Math.random()*100;
        if(num>50){
            return false;
        }else{
            return true;
        }
    }
}

如果想要展示上面的withDetail中的信息,就要在appliction.properties配置文件中,配置:

management.endpoint.health.show-details=always

源碼顯示:



自帶的health檢測器都是繼承AbstraceHealthIndicator抽象類。

所以除了繼承HealthIndicator接口來實現我們的自定義的檢測器,還可以繼承AbstraceHealthIndicator,重寫它的doHealthCheck()方法即可。


代碼如下:

@Component
public class MyDiskSpaceHealthIndicator extends AbstractHealthIndicator {

    private final FileStore fileStore;
    private final long thresholdBytes;

    @Autowired
    public MyDiskSpaceHealthIndicator(
            @Value("${health.filestore.path:/}") String path,
            @Value("${health.filestore.threshold.bytes:10485760}") long thresholdBytes)
            throws IOException {
        fileStore = Files.getFileStore(Paths.get(path));
        this.thresholdBytes = thresholdBytes;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        long diskFreeInBytes = fileStore.getUnallocatedSpace();
        if (diskFreeInBytes >= thresholdBytes) {
            builder.up();
        } else {
            builder.down();
        }
        long totalSpaceInBytes = fileStore.getTotalSpace();
        builder.withDetail("disk.free", diskFreeInBytes);
        builder.withDetail("disk.total", totalSpaceInBytes);
    }
}


重啓項目,訪問:http://localhost:8888/actuator/health  顯示:


(3) /threaddump  訪問路徑/actuator/threaddump ,這個端點是返回應用中的線程信息。:



(4) /httptrace 訪問路徑:/actuator/httptrace 用來返回基本的HTTP跟蹤信息,返回了WEB的請求情況。



以上的這些監控端點在Spring cloud中都有很大的作用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章