廢話不多說,直接上乾貨 一、actuator spring-boot內建效能監控,需要引入依賴包如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
二、自訂Endpoint 繼承AbstractEndpoint類,實現invoke方法,返回需要展示的效能資訊。 建構函式必須傳入一個指定的id,該id將作為訪問路徑的依據,比如內建的endpoint有health,metrics 建構函式必須傳入sensitive變數,該變數建議為true,方便後面的安全管控 舉個例子
public class RunTimeStatisticsEndpoint extends AbstractEndpoint<Map<String, Object>> {public RunTimeStatisticsEndpoint() {super("runTime", true);}@Overridepublic Map<String, Object> invoke() {return ControllerInfo.instance().getCache();}}
三、安全 隨時可以訪問監控的效能指標,對於系統來說,這樣不安全。解決辦法是,可以結合spring-security來進行加密 引入依賴包如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
加入以下配置
spring: application: name: myfee jackson: serialization: indent-output: true date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+08security: basic: enabled: true path: /xxx/admin user: name: xxx password: xxx management: security: role: SUPERUSER enabled: true port: 8888 context-path: /xxx/adminendpoints: health: sensitive: true enabled: true metrics: sensitive: true enabled: true
其中設定了使用者名稱,密碼,對於admin這個路徑才進行攔截。 值得說明的是,如果不設定連接埠號碼,那麼將和項目的連接埠號碼一致,比如8080。 那麼訪問路徑為http://ip:8080/項目contextPath/這裡指定的context-path 也就是http://ip:8080/項目contextPath/xxx/admin 如果設定了連接埠號碼,比如這裡的8888,那麼訪問路徑變為http://ip:8888/這裡指定的context-path 也就是http://ip:8888/xxx/admin