
定義
Actuator 為springboot項目提供了很全面的監(jiān)控和審查,通過啟用和公開endpoints,可以很方便的查看項目中的一些指標。
添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
關于Endpoints
Actuator提供了很多內置的Endpoints,每一個EP都可以啟用/禁用 和 公開。
當然,EP只有啟動并公開之后,才會真正生效。
如何啟用/禁用Endpoints?
除了 shutdown 之外,所有的EP都是默認啟用的,如果要啟用/禁用EP,可使用以下配置:
management.endpoint.<id>.enabled=true/false?。
比如啟用 shutdown :
management.endpoint.shutdown.enabled=true
為了安全,在生產(chǎn)環(huán)境不建議啟用所有的EP,而是按需啟用,所以要首先禁用默認行為,然后啟用需要的EP,如下:
management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true
這樣只有啟用的EP才會加載到上下文。
這樣只是啟用和禁用了EP,但是否暴露出去,還需要單獨的配置。
如何暴露/隱藏 Endpoints?
EP會暴露應用的很多指標,所以非常重要和敏感,在生產(chǎn)環(huán)境一定要做好選擇和安全防護。
暴露和隱藏使用以下配置:
# 針對 JMX 規(guī)范協(xié)議
management.endpoints.jmx.exposure.exclude
management.endpoints.jmx.exposure.include *
# 針對http協(xié)議
management.endpoints.web.exposure.exclude
management.endpoints.web.exposure.include health
使用 include 暴露Ep,使用 exclude 隱藏 Ep,其中 exclude 優(yōu)先級高于 include。
星號 * 表示全部的,另外星號在properties和yaml中有一點不同:
在YAML中星號(*)具有特殊的含義,所以需要用雙引號括起來,如 "*"
比如要隱藏所有的并僅僅啟用health和info:
management.endpoints.web.exposure.include=health,info
比如要暴露所有并禁用env和beans:
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
前文有述,EP包括很多敏感信息,一定要注意安全,那應該如何確保安全?
如何實現(xiàn)Http Endpoints 安全加固
如果項目中使用了 spring security 或 shiro 等安全框架,可以把EP放在安全框架之后,和其他業(yè)務API一樣保護起來。
或者,也可以使用RequestMatcher對象來配合使用,以控制某些用戶具備訪問權限,比如:
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration(proxyBeanMethods = false)
public class MySecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests((requests) -> requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
http.httpBasic();
return http.build();
}
}
這樣只有具備 ENDPOINT_ADMIN 角色的用戶才可以訪問EP。
如何通過頁面訪問各類指標
通過項目的 ip:port /actuator ,比如 localhost:8080/actuator:

可以通過配置修改路徑:
# 修改 /actutor 為 /manage
management.endpoints.web.base-path=/manage
# 修改特定指標 /health 為 /myhealth
management.endpoints.web.path-mapping.health=myhealth
# 修改訪問端口(默認和server.port相同)
management.server.port=8036