Spring Boot Actuator詳解與深入應用(一):Actuator 1.x

aoho發表於2019-03-03

《Spring Boot Actuator詳解與深入應用》預計包括三篇,第一篇重點講Spring Boot Actuator 1.x的應用與定製端點;第二篇將會對比Spring Boot Actuator 2.x 與1.x的區別,以及應用和定製2.x的端點;第三篇將會介紹Actuator metric指標與Prometheus和Grafana的使用結合。這部分內容很常用,且較為入門,歡迎大家的關注。

Actuator是什麼

Spring Boot Actuator提供了生產上經常用到的功能(如健康檢查,審計,指標收集,HTTP跟蹤等),幫助我們監控和管理Spring Boot應用程式。這些功能都可以通過JMX或HTTP端點訪問。

通過引入相關的依賴,即可監控我們的應用程式,收集指標、瞭解流量或資料庫的狀態變得很簡單。該庫的主要好處是我們可以獲得生產級工具,而無需自己實際實現這些功能。與大多數Spring模組一樣,我們可以通過多種方式輕鬆配置或擴充套件它。

Actuator還可以與外部應用監控系統整合,如Prometheus,Graphite,DataDog,Influx,Wavefront,New Relic等等。 這些系統為您提供出色的儀表板,圖形,分析和警報,以幫助我們在一個統一介面監控和管理應用服務。

本文將會介紹Spring Boot Actuator 1.x 包括其中的端點(HTTP端點)、配置管理以及擴充套件和自定義端點。

快速開始

引入如下的依賴:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
複製程式碼

Spring Boot Actuator 1.x

在1.x中,Actuator遵循讀寫模型,這意味著我們可以從中讀取資訊或寫入資訊。我們可以檢索指標或我們的應用程式的健康狀況,當然我們也可以優雅地終止我們的應用程式或更改我們的日誌配置。Actuator通過Spring MVC暴露其HTTP端點。

端點

當引入的Actuator的版本為1.x時,啟動應用服務,可以控制檯輸出如下的端點資訊:

Spring Boot Actuator詳解與深入應用(一):Actuator 1.x

我們介紹一下常用的endpoints:

  • /health:顯示應用程式執行狀況資訊(通過未經身份驗證的連線訪問時的簡單“狀態”或經過身份驗證時的完整訊息詳細資訊),它預設不敏感
  • /info:顯示應用程式資訊,預設情況下不敏感
  • /metrics:顯示當前應用程式的“指標”資訊,它預設也很敏感
  • /trace:顯示跟蹤資訊(預設情況下是最後幾個HTTP請求)

有些端點預設並不會被開啟,如/shutdown。

配置端點

我們可以自定義每個端點的屬性,按照如下的格式:

endpoints.[endpoint name].[property to customize]
複製程式碼

可以自定義的屬性有如下三個:

  • id,暴露的http端點地址
  • enabled,是否開啟
  • sensitive,當為true時,需要認證之後才會通過http獲取到敏感資訊

我們在配置檔案中增加如下的配置,將會定製/beans端點。

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
endpoints.beans.enabled=true
複製程式碼

/health端點

/health端點用於監控執行的服務例項狀態,當服務例項下線或者因為其他的原因變得異常(如DB連線不上,磁碟缺少空間)時,將會及時通知運維人員。

在預設未授權的情況下,通過HTTP的方式僅會返回如下的簡單資訊:

{
	"status": "UP"
}
複製程式碼

獲取詳細的health資訊

我們進行如下的配置:

endpoints:
  health:
    id: chealth
    sensitive: false

management.security.enabled: false
複製程式碼

如上一小節所述,我們更改了/health端點的訪問路徑為/chealth,並將安全授權關閉。訪問http://localhost:8005/chealth將會得到如下的結果。

{
	"status": "UP",
	"healthCheck": {
		"status": "UP"
	},
	"diskSpace": {
		"status": "UP",
		"total": 999995129856,
		"free": 762513104896,
		"threshold": 10485760
	}
}
複製程式碼

自定義health的資訊

我們還可以定製實現health指示器。它可以收集特定於應用程式的任何型別的自定義執行狀況資料,並通過/health端點訪問到定義的資訊。

@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() {
        // Our logic to check health
        return 0;
    }
}
複製程式碼

實現HealthIndicator介面,並覆寫其中的health()方法即可自定義我們的/health端點。

/info端點

通過/info端點,我們可以為應用服務定義一些基本資訊:

info.app.name=Spring Sample Application
info.app.description=This is my first spring boot application
info.app.version=1.0.0
複製程式碼

我們在如上的配置中定義了服務名、描述和服務的版本號。

/metrics端點

/metrics端點展示了OS、JVM和應用級別的指標資訊。當開啟之後,我們可以獲取記憶體、堆、執行緒、執行緒池、類載入和HTTP等資訊。

{
	"mem": 417304,
	"mem.free": 231678,
	"processors": 4,
	"instance.uptime": 248325,
	"uptime": 250921,
	"systemload.average": 1.9541015625,
	"heap.committed": 375296,
	"heap.init": 393216,
	"heap.used": 143617,
	"heap": 5592576,
	"nonheap.committed": 43104,
	"nonheap.init": 2496,
	"nonheap.used": 42010,
	"nonheap": 0,
	"threads.peak": 30,
	"threads.daemon": 18,
	"threads.totalStarted": 46,
	"threads": 20,
	"classes": 6020,
	"classes.loaded": 6020,
	"classes.unloaded": 0,
	"gc.ps_scavenge.count": 3,
	"gc.ps_scavenge.time": 35,
	"gc.ps_marksweep.count": 1,
	"gc.ps_marksweep.time": 29,
	"httpsessions.max": -1,
	"httpsessions.active": 0,
	"gauge.response.info": 38.0,
	"counter.status.200.info": 1
}
複製程式碼

定製metrics端點

為了收集自定義的metrics,Actuator支援單數值記錄的功能,簡單的增加/減少計數功能。如下的實現,我們將登入成功和失敗的次數作為自定義指標記錄下來。

@Service
public class LoginServiceImpl implements LoginService {
    private final CounterService counterService;

    @Autowired
    public LoginServiceImpl(CounterService counterService) {
        this.counterService = counterService;
    }

    @Override
    public Boolean login(String userName, char[] password) {
        boolean success;
        if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
            counterService.increment("counter.login.success");
            success = true;
        } else {
            counterService.increment("counter.login.failure");
            success = false;
        }
        return success;
    }
}
複製程式碼

再次訪問/metrics,發現多瞭如下的指標資訊。登入嘗試和其他安全相關事件在Actuator中可用作審計事件。

{
	"gauge.response.metrics": 2.0,
	"gauge.response.test": 3.0,
	"gauge.response.star-star.favicon.ico": 1.0,
	"counter.status.200.star-star.favicon.ico": 10,
	"counter.status.200.test": 6,
	"counter.login.failure": 6,
	"counter.status.200.metrics": 4
}
複製程式碼

自定義端點

除了使用Spring Boot Actuator提供的端點,我們也可以定義一個全新的端點。

首先,我們需要實現Endpoint介面:

@Component
public class CustomEndpoint implements Endpoint<List<String>> {
    @Override
    public String getId() {
        return "custom";
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public boolean isSensitive() {
        return false;
    }

    @Override
    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;
    }
}
複製程式碼

getId()方法用於匹配訪問這個端點,當我們訪問/custom時,將會呼叫invoke()我們自定義的邏輯。 另外兩個方法,用於設定是否開啟和是否為敏感的端點。

[ "This is message 1", "This is message 2" ]
複製程式碼

進一步定製

出於安全考慮,我們可能選擇通過非標準埠暴露Actuator端點。通過management.port屬性來配置它。

另外,正如我們已經提到的那樣,在1.x. Actuator基於Spring Security配置自己的安全模型,但獨立於應用程式的其餘部分。

因此,我們可以更改management.address屬性以限制可以通過網路訪問端點的位置:

#port used to expose actuator
management.port=8081 
 
#CIDR allowed to hit actuator
management.address=127.0.0.1 
複製程式碼

此外,除了/info端點,其他所有的端點預設都是敏感的,如果引入了Spring Security,我們通過在配置檔案中定義這些安全的屬性(username, password, role)來確保內建端點的安全。

總結

Spring Boot Actuator為我們的應用服務在生產環境提供了很多開箱即用的功能。本文主要講解了Spring Boot Actuator 1.x的深入使用。我們既可以使用內建的端點(如/health,/info等),可以在這些端點的基礎進行擴充套件和定製,還可以自定義全新的端點,在使用方式上顯得非常靈活。 本文原始碼:github.com/keets2012/S…

訂閱最新文章,歡迎關注我的公眾號

微信公眾號

參考

  1. Actuator docs
  2. Spring Boot Actuator

相關文章