點(diǎn)擊關(guān)注公眾號(hào),Java干貨及時(shí)送達(dá)
來源: blog.c sdn.net/yunfeather/ article/details/122581536
pom.xml
info
beans
conditions
heapdump
shutdown
mappings
threaddump
loggers 端點(diǎn)
metrics 端點(diǎn)
自定義Endpoint
自定義監(jiān)控端點(diǎn)常用注解
使用Filter對(duì)訪問actuator做限制
Spring Boot Monitor做監(jiān)控頁面
SpringBoot自帶監(jiān)控功能Actuator,可以幫助實(shí)現(xiàn)對(duì)程序內(nèi)部運(yùn)行情況監(jiān)控,比如監(jiān)控狀況、Bean加載情況、環(huán)境變量、日志信息、線程信息等
配置Actuatorpom.xml
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
瀏覽器打開鏈接http://localhost:8080/actuator/
可以看到所有支持的連接,默認(rèn)只有
/actuator
/actuator/health
/actuator/health/{component}
/actuator/health/{component}/{instance}
/actuator/info
bean加載情況http://localhost:8080/actuator/beans
具體的使用方法:
引入上述的依賴jar
通過下面的配置啟用所有的監(jiān)控端點(diǎn),默認(rèn)情況下,這些端點(diǎn)是禁用的;
management:
endpoints:
web:
exposure:
include: "*"
“*”號(hào)代表啟用所有的監(jiān)控端點(diǎn),可以單獨(dú)啟用,例如,health
,info
,metrics
等
Actuator 的 REST 接口
Actuator 監(jiān)控分成兩類:原生端點(diǎn)和用戶自定義端點(diǎn);自定義端點(diǎn)主要是指擴(kuò)展性,用戶可以根據(jù)自己的實(shí)際應(yīng)用,定義一些比較關(guān)心的指標(biāo),在運(yùn)行期進(jìn)行監(jiān)控。
原生端點(diǎn)是在應(yīng)用程序里提供眾多 Web 接口,通過它們了解應(yīng)用程序運(yùn)行時(shí)的內(nèi)部狀況。原生端點(diǎn)又可以分成三類:
應(yīng)用配置類:可以查看應(yīng)用在運(yùn)行期的靜態(tài)信息:例如自動(dòng)配置信息、加載的 springbean 信息、yml 文件配置信息、環(huán)境信息、請(qǐng)求映射信息;
度量指標(biāo)類:主要是運(yùn)行期的動(dòng)態(tài)信息,例如堆棧、請(qǐng)求連、一些健康指標(biāo)、metrics 信息等;
操作控制類:主要是指 shutdown,用戶可以發(fā)送一個(gè)請(qǐng)求將應(yīng)用的監(jiān)控功能關(guān)閉。
Actuator 提供了 13 個(gè)接口,具體如下表所示。
GET /auditevents 顯示應(yīng)用暴露的審計(jì)事件 (比如認(rèn)證進(jìn)入、訂單失敗) GET /beans 描述應(yīng)用程序上下文里全部的 Bean,以及它們的關(guān)系 GET /conditions 就是 1.0 的 /autoconfig ,提供一份自動(dòng)配置生效的條件情況,記錄哪些自動(dòng)配置條件通過了,哪些沒通過 GET /configprops 描述配置屬性(包含默認(rèn)值)如何注入Bean GET /env 獲取全部環(huán)境屬性 GET /env/{name} 根據(jù)名稱獲取特定的環(huán)境屬性值 GET /flyway 提供一份 Flyway 數(shù)據(jù)庫遷移信息 GET /liquidbase 顯示Liquibase 數(shù)據(jù)庫遷移的纖細(xì)信息 GET /health 報(bào)告應(yīng)用程序的健康指標(biāo),這些值由 HealthIndicator 的實(shí)現(xiàn)類提供 GET /heapdump dump 一份應(yīng)用的 JVM 堆信息 GET /httptrace 顯示HTTP足跡,最近100個(gè)HTTP request/repsponse GET /info 獲取應(yīng)用程序的定制信息,這些信息由info打頭的屬性提供 GET /logfile 返回log file中的內(nèi)容(如果 logging.file 或者 logging.path 被設(shè)置) GET /loggers 顯示和修改配置的loggers GET /metrics 報(bào)告各種應(yīng)用程序度量信息,比如內(nèi)存用量和HTTP請(qǐng)求計(jì)數(shù) GET /metrics/{name} 報(bào)告指定名稱的應(yīng)用程序度量值 GET /scheduledtasks 展示應(yīng)用中的定時(shí)任務(wù)信息 GET /sessions 如果我們使用了 Spring Session 展示應(yīng)用中的 HTTP sessions 信息 POST /shutdown 關(guān)閉應(yīng)用程序,要求endpoints.shutdown.enabled設(shè)置為true GET /mappings 描述全部的 URI路徑,以及它們和控制器(包含Actuator端點(diǎn))的映射關(guān)系 GET /threaddump 獲取線程活動(dòng)的快照
命令詳解
在 Spring Boot 2.x 中為了安全期間,Actuator 只開放了兩個(gè)端點(diǎn)/actuator/health
和/actuator/info
。可以在配置文件中設(shè)置打開。
可以打開所有的監(jiān)控點(diǎn)
management:
endpoints:
web:
exposure:
include: "*"
也可以選擇打開部分
management:
endpoints:
web:
exposure:
exclude: beans,trace
Actuator 默認(rèn)所有的監(jiān)控點(diǎn)路徑都在/actuator/*
,當(dāng)然如果有需要這個(gè)路徑也支持定制。
management:
endpoints:
web:
base-path: /manage #記得要加上/
設(shè)置完重啟后,再次訪問地址就會(huì)變成/manage/*
Actuator 幾乎監(jiān)控了應(yīng)用涉及的方方面面,我們重點(diǎn)講述一些經(jīng)常在項(xiàng)目中常用的命令。
health
health 主要用來檢查應(yīng)用的運(yùn)行狀態(tài),這是我們使用最高頻的一個(gè)監(jiān)控點(diǎn)。通常使用此接口提醒我們應(yīng)用實(shí)例的運(yùn)行狀態(tài),以及應(yīng)用不”健康“的原因,比如數(shù)據(jù)庫連接、磁盤空間不夠等。
默認(rèn)情況下 health 的狀態(tài)是開放的,添加依賴后啟動(dòng)項(xiàng)目,訪問:http://localhost:8080/actuator/health
即可看到應(yīng)用的狀態(tài)。
"status" : "UP"
要想查看詳細(xì)的應(yīng)用健康信息需要配置management.endpoint.health.show-details
的值為always,配置之后我們?cè)俅卧L問http://localhost:8080/actuator/health
,獲取的信息如下:
"status": "UP",
"components": {
"diskSpace": {
"status": "UP",
"details": {
"total": 236510507008,
"free": 223361744896,
"threshold": 10485760
},
"ping": {
"status": "UP"
Spring boot的健康信息都是從ApplicationContext
中的各種HealthIndicator Beans
中收集到的,Spring boot框架中包含了大量的HealthIndicators
的實(shí)現(xiàn)類,當(dāng)然你也可以實(shí)現(xiàn)自己認(rèn)為的健康狀態(tài)。
默認(rèn)情況下,最終的 Spring Boot 應(yīng)用的狀態(tài)是由HealthAggregator
匯總而成的,匯總的算法是:
設(shè)置狀態(tài)碼順序:
setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);
。過濾掉不能識(shí)別的狀態(tài)碼。
如果無任何狀態(tài)碼,整個(gè) Spring Boot 應(yīng)用的狀態(tài)是
UNKNOWN
。將所有收集到的狀態(tài)碼按照 1 中的順序排序。
返回有序狀態(tài)碼序列中的第一個(gè)狀態(tài)碼,作為整個(gè) Spring Boot 應(yīng)用的狀態(tài)。
health 通過合并幾個(gè)健康指數(shù)檢查應(yīng)用的健康情況。Spring boot框架自帶的HealthIndicators
目前包括:
CassandraHealthIndicator Checks that a Cassandra database is up.DiskSpaceHealthIndicator
Checks for low disk space.DataSourceHealthIndicator
Checks that a connection toDataSource
can be obtained.ElasticsearchHealthIndicator
Checks that an Elasticsearch cluster is up.InfluxDbHealthIndicator
Checks that an InfluxDB server is up.JmsHealthIndicator
Checks that a JMS broker is up.MailHealthIndicator
Checks that a mail server is up.MongoHealthIndicator
Checks that a Mongo database is up.Neo4jHealthIndicator
Checks that a Neo4j server is up.RabbitHealthIndicator
Checks that a Neo4j server is up.RedisHealthIndicator
Checks that a Redis server is up.SolrHealthIndicator
Checks that a Solr server is up.
舉個(gè)例子,如果你的應(yīng)用使用 Redis,RedisHealthindicator
將被當(dāng)作檢查的一部分;如果使用 MongoDB,那么MongoHealthIndicator
將被當(dāng)作檢查的一部分。
可以在配置文件中關(guān)閉特定的健康檢查指標(biāo),比如關(guān)閉 redis 的健康檢查:
management:
health:
redise:
enabled: false
默認(rèn),所有的這些健康指標(biāo)被當(dāng)作健康檢查的一部分。
自定義 HealthIndicator 健康檢查
有時(shí)候需要提供自定義的健康狀態(tài)檢查信息,你可以通過實(shí)現(xiàn)HealthIndicator
的接口來實(shí)現(xiàn),并將該實(shí)現(xiàn)類注冊(cè)為spring bean。你需要實(shí)現(xiàn)其中的health()
方法,并返回自定義的健康狀態(tài)響應(yīng)信息,該響應(yīng)信息應(yīng)該包括一個(gè)狀態(tài)碼和要展示詳細(xì)信息。例如,下面就是一個(gè)接口HealthIndicator
的實(shí)現(xiàn)類:
@Component
public class MyHealthIndicator 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();
}
}
另外,除了Spring boot定義的幾個(gè)狀態(tài)類型,我們也可以自定義狀態(tài)類型,用來表示一個(gè)新的系統(tǒng)狀態(tài)。在這種情況下,你還需要實(shí)現(xiàn)接口HealthAggregator
,或者通過配置management.health.status.order
來繼續(xù)使用HealthAggregator
的默認(rèn)實(shí)現(xiàn)。
例如,在你自定義的健康檢查HealthIndicator
的實(shí)現(xiàn)類中,使用了自定義的狀態(tài)類型FATAL
,為了配置該狀態(tài)類型的嚴(yán)重程度,你需要在application的配置文件中添加如下配置:
management:
health:
status:
order: FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP
在做健康檢查時(shí),響應(yīng)中的HTTP狀態(tài)碼反應(yīng)了整體的健康狀態(tài),(例如,UP 對(duì)應(yīng) 200, 而OUT_OF_SERVICE
和DOWN
對(duì)應(yīng) 503)。同樣,你也需要為自定義的狀態(tài)類型設(shè)置對(duì)應(yīng)的HTTP狀態(tài)碼,例如,下面的配置可以將FATAL
映射為 503(服務(wù)不可用):
management:
health:
status:
http-mapping:
FATAL: 503
下面是內(nèi)置健康狀態(tài)類型對(duì)應(yīng)的HTTP狀態(tài)碼列表:
Status Mapping OUT_OF_SERVICE SERVICE_UNAVAILABLE (503) DOWN SERVICE_UNAVAILABLE (503) UP No mapping by default, so http status is 200 UNKNOWN No mapping by default, so http status is 200
info
info 就是我們自己配置在配置文件中以 info 開頭的配置信息,比如我們?cè)谑纠?xiàng)目中的配置是:
info:
app:
name:
spring-boot-actuator
version: 1.0.0
test: test
啟動(dòng)示例項(xiàng)目,訪問:http://localhost:8080/actuator/info
返回部分信息如下:
beans
"app": {
"name": "spring-boot-actuator",
"version": "1.0.0",
"test":"test"
根據(jù)示例就可以看出,展示了 bean 的別名、類型、是否單例、類的地址、依賴等信息。
啟動(dòng)示例項(xiàng)目,訪問:http://localhost:8080/actuator/beans
返回部分信息如下:
"context": "application:8080:management",
"parent": "application:8080",
"beans": [
"bean": "embeddedServletContainerFactory",
"aliases": [
],
"scope": "singleton",
"type": "org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory",
"resource": "null",
"dependencies": [
]
},
{
"bean": "endpointWebMvcChildContextConfiguration",
"aliases": [
],
"scope": "singleton",
"type": "org.springframework.boot.actuate.autoconfigure.EndpointWebMvcChildContextConfiguration$$EnhancerBySpringCGLIB$$a4a10f9d",
"resource": "null",
"dependencies": [
]
conditions
}
}
]
Spring Boot 的自動(dòng)配置功能非常便利,但有時(shí)候也意味著出問題比較難找出具體的原因。使用 conditions 可以在應(yīng)用運(yùn)行時(shí)查看代碼了某個(gè)配置在什么條件下生效,或者某個(gè)自動(dòng)配置為什么沒有生效。
啟動(dòng)示例項(xiàng)目,訪問:http://localhost:8080/actuator/conditions
返回部分信息如下:
heapdump
"positiveMatches": {
"DevToolsDataSourceAutoConfiguration": {
"notMatched": [
"condition": "DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition",
"message": "DevTools DataSource Condition did not find a single DataSource bean"
],
"matched": [ ]
},
"RemoteDevToolsAutoConfiguration": {
"notMatched": [
"condition": "OnPropertyCondition",
"message": "@ConditionalOnProperty (spring.devtools.remote.secret) did not find property 'secret'"
],
"matched": [
"condition": "OnClassCondition",
"message": "@ConditionalOnClass found required classes 'javax.servlet.Filter', 'org.springframework.http.server.ServerHttpRequest'; @ConditionalOnMissingClass did not find unwanted class"
返回一個(gè) GZip 壓縮的 JVM 堆 dump
啟動(dòng)示例項(xiàng)目,訪問:http://localhost:8080/actuator/heapdump
會(huì)自動(dòng)生成一個(gè) Jvm 的堆文件 heapdump,我們可以使用 JDK 自帶的 Jvm 監(jiān)控工具 VisualVM 打開此文件查看內(nèi)存快照。類似如下圖:
圖片shutdown
開啟接口優(yōu)雅關(guān)閉 Spring Boot 應(yīng)用,要使用這個(gè)功能首先需要在配置文件中開啟:
management:
endpoint:
shutdown:
enabled: true
配置完成之后,啟動(dòng)示例項(xiàng)目,使用 curl 模擬 post 請(qǐng)求訪問 shutdown 接口。
shutdown 接口默認(rèn)只支持 post 請(qǐng)求。
curl -X POST "http://localhost:8080/actuator/shutdown"
"message": "Shutting down, bye..."
此時(shí)你會(huì)發(fā)現(xiàn)應(yīng)用已經(jīng)被關(guān)閉。
mappings
描述全部的 URI 路徑,以及它們和控制器的映射關(guān)系
啟動(dòng)示例項(xiàng)目,訪問:http://localhost:8080/actuator/mappings
返回部分信息如下:
threaddump
"/**/favicon.ico": {
"bean": "faviconHandlerMapping"
},
"{[/hello]}": {
"bean": "requestMappingHandlerMapping",
"method": "public java.lang.String com.neo.controller.HelloController.index()"
},
"{[/error]}": {
"bean": "requestMappingHandlerMapping",
"method": "public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)"
/threaddump
接口會(huì)生成當(dāng)前線程活動(dòng)的快照。這個(gè)功能非常好,方便我們?cè)谌粘6ㄎ粏栴}的時(shí)候查看線程的情況。 主要展示了線程名、線程ID、線程的狀態(tài)、是否等待鎖資源等信息。
啟動(dòng)示例項(xiàng)目,訪問:http://localhost:8080/actuator/threaddump
返回部分信息如下:
"threadName": "http-nio-8088-exec-6",
"threadId": 49,
"blockedTime": -1,
"blockedCount": 0,
"waitedTime": -1,
"waitedCount": 2,
"lockName": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@1630a501",
"lockOwnerId": -1,
"lockOwnerName": null,
"inNative": false,
"suspended": false,
"threadState": "WAITING",
"stackTrace": [
"methodName": "park",
"fileName": "Unsafe.java",
"lineNumber": -2,
"className": "sun.misc.Unsafe",
"nativeMethod": true
},
"methodName": "run",
"fileName": "TaskThread.java",
"lineNumber": 61,
"className": "org.apache.tomcat.util.threads.TaskThread$WrappingRunnable",
"nativeMethod": false
],
"lockInfo": {
"className": "java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject",
"identityHashCode": 372286721
生產(chǎn)出現(xiàn)問題的時(shí)候,可以通過應(yīng)用的線程快照來檢測(cè)應(yīng)用正在執(zhí)行的任務(wù)。
loggers 端點(diǎn)
訪問http://localhost:8080/actuator/loggers
可以查看當(dāng)前應(yīng)用的日志級(jí)別等信息:
圖片
這里面本身并不特別,但是有一個(gè)功能卻非常有用,比如我們生產(chǎn)環(huán)境日志級(jí)別一般都是 info,但是現(xiàn)在有一個(gè) bug 通過 info 級(jí)別無法排查,那么我們就可以臨時(shí)修改 log 級(jí)別。
比如上圖中的 ROOT 節(jié)點(diǎn)是 info 級(jí)別,那么我們可以通過 postman 等工具來發(fā)一個(gè) post 請(qǐng)求修改日志級(jí)別。
圖片
修改之后就會(huì)發(fā)現(xiàn),日志由原來的 info 變成了 debug:
圖片metrics 端點(diǎn)
metrics 是一個(gè)非常重要的監(jiān)控端點(diǎn),其監(jiān)控內(nèi)容覆蓋了 JVM 內(nèi)存、堆、類加載、處理器和 tomcat 容器等一些重要指標(biāo):
圖片
可以看到這里面包含了非常多的指標(biāo),任意訪問一個(gè)指標(biāo)就可以查看對(duì)應(yīng)的指標(biāo)信息:
圖片自定義Endpoint
自定義配置來控制是否開啟過濾
actuator:
自定義監(jiān)控端點(diǎn)常用注解
filter:
switch: false
自定義一個(gè)監(jiān)控端點(diǎn)主要有如下常用注解:
@Endpoint:定義一個(gè)監(jiān)控端點(diǎn),同時(shí)支持 HTTP 和 JMX 兩種方式。
@WebEndpoint:定義一個(gè)監(jiān)控端點(diǎn),只支持 HTTP 方式。
@JmxEndpoint:定義一個(gè)監(jiān)控端點(diǎn),只支持 JMX 方式。
以上三個(gè)注解作用在類上,表示當(dāng)前類是一個(gè)監(jiān)控端點(diǎn),另外還有一些注解會(huì)用在方法和參數(shù)上:
@ReadOperation:作用在方法上,可用來返回端點(diǎn)展示的信息(通過 Get 方法請(qǐng)求)。
@WriteOperation:作用在方法上,可用來修改端點(diǎn)展示的信息(通過 Post 方法請(qǐng)求)。
@DeleteOperation:作用在方法上,可用來刪除對(duì)應(yīng)端點(diǎn)信息(通過 Delete 方法請(qǐng)求)。
@Selector:作用在參數(shù)上,用來定位一個(gè)端點(diǎn)的具體指標(biāo)路由。
一般情況下,是沒必要自定義Endpoint的,但是也不排除特殊情況,我這里自定義一個(gè)Endpoint,用來往request里放一個(gè)user對(duì)象,這個(gè)user是用來做測(cè)試的,用于下面突破filter用的(下面再說),這里先說怎么增查這個(gè)user。
過程如下:
使用
@Endpoint
注解相應(yīng)的類,作為Actuator的一個(gè)endpoint。注解要指定id,這個(gè)id作為訪問路徑,比如這里是/actuator/super
;@ReadOperation
來注解查詢接口,如果要根據(jù)路徑做查詢,要用@Selector
注解方法參數(shù);注意這地方是@Selector String arg0
,這個(gè)arg0不能改變,改成其他的,開放出去的接口還是/{arg0}
,這就導(dǎo)致你的方法無法正常獲取參數(shù)值。@WriteOperation
來注解修改接口,注意請(qǐng)求數(shù)據(jù)必須是json,而且參數(shù)不像controller中那么靈活,不能將實(shí)體作為參數(shù),要把實(shí)體中相應(yīng)的屬性拿出來做參數(shù)。這里在增加用戶時(shí),往request里放一個(gè)user對(duì)象。
SuperEndPoint :
package com.cff.springbootwork.actuator.endpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Endpoint(id = "super")
public class SuperEndPoint {
private Map users = new ConcurrentHashMap<>();
@ReadOperation
public Set users() {
return users.keySet();
}
@ReadOperation
public SuperUser usersIdentify(@Selector String arg0) {
return users.get(arg0);
}
@WriteOperation
public Set set(String userName, String passwd) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
if (request != null) {
SuperUser superUser = new SuperUser();
superUser.setUserName(userName);
superUser.setPasswd(passwd);
request.getSession().setAttribute("superUser", superUser);
users.put(superUser.getUserName(), superUser);
}
return users.keySet();
}
public static class SuperUser {
private String userName;
private String passwd;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
}
還要將Endpoint注冊(cè)為bean
MvcEndPointConfig:
package com.cff.springbootwork.actuator;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.cff.springbootwork.actuator.endpoint.SuperEndPoint;
@Configuration
@ServletComponentScan
public class MvcEndPointConfig {
@Bean
使用Filter對(duì)訪問actuator做限制
@ConditionalOnEnabledEndpoint
public SuperEndPoint superEndPoint() {
return new SuperEndPoint();
}
}
上面已經(jīng)說了,actuator的接口要做保護(hù),我這里就用filter對(duì)接口做最簡(jiǎn)單的保護(hù)。
對(duì)
/actuator/*下
所有路徑做過濾,并用actuator.filter.switch
屬性對(duì)filter做開關(guān);如果時(shí)
/actuator/super
路徑的post操作,放行它,它將會(huì)往request中放一個(gè)對(duì)象;其他
/actuator/*下
路徑要判斷request中有沒有user對(duì)象,沒有就返回錯(cuò)誤提示。
ActuatorPermissionFilter :
package com.cff.springbootwork.actuator.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
@WebFilter(urlPatterns = "/actuator/*", filterName = "actuatorPermissionFilter")
@Order(1) // 指定過濾器的執(zhí)行順序,值越大越靠后執(zhí)行
public class ActuatorPermissionFilter implements Filter {
private String excludePath = "actuator/super";
@Value("${actuator.filter.switch}")
Boolean actuatorSwitch;
@Override
public void init(FilterConfig filterConfig) {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (actuatorSwitch && !(request.getRequestURI().endsWith(excludePath)
&& request.getMethod().equals(HttpMethod.POST.toString()))) {
Object user = request.getSession().getAttribute("superUser");
if (user == null) {
// 未登錄,返回?cái)?shù)據(jù)
ObjectMapper mapper = new ObjectMapper();
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
mapper.writeValue(response.getWriter(), "您沒有權(quán)限訪問該接口,請(qǐng)使用自定義的登錄接口設(shè)置superUser后使用!");
return;
}
}
filterChain.doFilter(servletRequest, servletResponse);
@Override
public void destroy() {
}
}
Spring Boot Monitor做監(jiān)控頁面
額外引入依賴
cn.pomit
spring-boot-monitor
0.0.1
Spring Boot Monitor是一個(gè)對(duì)Spring boot admin監(jiān)控工具做修改并適配單機(jī)的監(jiān)控工具,完美繼承了Spring boot admin的風(fēng)格,直接使用actuator的指標(biāo)進(jìn)行顯示。
Spring Boot Monitor官網(wǎng):https://www.pomit.cn/SpringBootMonitor
前面maven依賴中,已經(jīng)說明依賴spring-boot-monitor,這時(shí),無需其他配置.
訪問http://127.0.0.1:8080/monitor
, 自動(dòng)跳轉(zhuǎn)到Spring Boot Monitor的監(jiān)控頁面。
圖片
Spring Boot Monitor的監(jiān)控頁面和Spring boot admin的一模一樣,前端的功能也一模一樣。
圖片
可以對(duì)Spring boot的各項(xiàng)指標(biāo)一目了然,還可以進(jìn)行簡(jiǎn)單的操作。
當(dāng)然,如果Spring boot actuator的指標(biāo)被限制了,它也拿不到相應(yīng)的指標(biāo)了,因?yàn)樗侵苯诱?qǐng)求actuator接口的。
特別聲明:以上內(nèi)容(如有圖片或視頻亦包括在內(nèi))為自媒體平臺(tái)“網(wǎng)易號(hào)”用戶上傳并發(fā)布,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.