Actuator簡(jiǎn)介
什么是Spring Boot Actuator?
- Spring Boot Actuator 模塊提供了生產(chǎn)級(jí)別的功能,比如健康檢查,審計(jì),指標(biāo)收集,HTTP跟蹤等,幫助我們監(jiān)控和管理Spring Boot應(yīng)用。
- 這個(gè)模塊是一個(gè)采集應(yīng)用內(nèi)部信息暴露給外部的模塊,上述的功能都可以通過(guò)HTTP和JMX訪問(wèn)。
- 因?yàn)楸┞秲?nèi)部信息的特性,Actuator也可以和一些外部的應(yīng)用監(jiān)控系統(tǒng)整合(Prometheus, Graphite, DataDog等)。這些監(jiān)控系統(tǒng)提供了出色的儀表板,圖形,分析和警報(bào),可幫助你通過(guò)一個(gè)統(tǒng)一友好的界面,監(jiān)視和管理你的應(yīng)用程序。
- Actuator使用Micrometer與這些外部應(yīng)用程序監(jiān)視系統(tǒng)集成。這樣一來(lái),只需很少的配置即可輕松集成外部的監(jiān)控系統(tǒng)。
Micrometer為Java 平臺(tái)上的性能數(shù)據(jù)收集提供了一個(gè)通用的API,應(yīng)用程序只需要使用Micrometer的通用API來(lái)收集性能指標(biāo)即可。Micrometer會(huì)負(fù)責(zé)完成與不同監(jiān)控系統(tǒng)的適配工作,這就使得切換監(jiān)控系統(tǒng)變得很容易。對(duì)比Slf4j之于Java Logger中的定位。
Endpoints介紹
Endpoints簡(jiǎn)介
Spring Boot提供了所謂endpoints(下文翻譯為端點(diǎn))用于外部系統(tǒng)與應(yīng)用程序進(jìn)行訪問(wèn)和交互。
例如,/health
端點(diǎn)提供了關(guān)于應(yīng)用健康情況的一些基礎(chǔ)信息。/metrics
端點(diǎn)提供了一些有用的應(yīng)用程序指標(biāo)(JVM 內(nèi)存使用、系統(tǒng)CPU使用等)。
Endpoints類型
Actuator模塊本來(lái)就有的端點(diǎn)我們稱之為原生端點(diǎn)。根據(jù)端點(diǎn)的作用的話,我們大概可以分為三大類:
- 應(yīng)用配置類: 獲取應(yīng)用程序中加載的應(yīng)用配置、環(huán)境變量、自動(dòng)化配置報(bào)告等與Spring Boot應(yīng)用密切相關(guān)的配置類信息。
- 度量指標(biāo)類: 獲取應(yīng)用程序運(yùn)行過(guò)程中用于監(jiān)控的度量指標(biāo),比如:內(nèi)存信息、線程池信息、HTTP請(qǐng)求統(tǒng)計(jì)等。
- 操作控制類: 提供了對(duì)應(yīng)用的關(guān)閉等操作類功能。
需要注意的就是:
- 每一個(gè)端點(diǎn)都可以通過(guò)配置來(lái)單獨(dú)禁用或者啟動(dòng)
- 不同于Actuator 1.x,Actuator 2.x 的大多數(shù)端點(diǎn)默認(rèn)被禁掉。 Actuator 2.x中的默認(rèn)端點(diǎn)增加了
/actuator
前綴。默認(rèn)暴露的兩個(gè)端點(diǎn)為/actuator/health
和/actuator/info
Endpoints清單
此處使用的是SpringBoot 2.2.8版本,詳情請(qǐng)查看Spring官方文件
Endpoint | HTTP方法 | 描述 |
---|---|---|
/actuator | GET | 查看有哪些Actuator endpoint是開放的 |
/actuator/auditevent | GET | 顯示應(yīng)用暴露的審計(jì)事件 (比如認(rèn)證進(jìn)入、訂單失敗),需要搭配Spring Security使用,示例代碼 |
/actuator/beans | GET | 查看當(dāng)前上下文中配置的所有的Bean |
/actuator/conditions | GET | 該端點(diǎn)用來(lái)獲取應(yīng)用的自動(dòng)化配置報(bào)告,其中包括所有自動(dòng)化配置的候選項(xiàng)。同時(shí)還列出了每個(gè)候選項(xiàng)自動(dòng)化配置的各個(gè)先決條件是否滿足。所以,該端點(diǎn)可以幫助我們方便的找到一些自動(dòng)化配置為什么沒(méi)有生效的具體原因。 |
/actuator/configprops | GET | 查看注入帶有@ConfigurationProperties類的properties配置的屬性和值,prefix代表前綴 |
/actuator/env (常用) | GET | 該端點(diǎn)與/configprops不同,它用來(lái)獲取應(yīng)用所有可用的環(huán)境屬性報(bào)告。包括:環(huán)境變量、JVM屬性、應(yīng)用的配置配置、命令行中的參數(shù)(但是會(huì)自動(dòng)過(guò)濾掉帶有key、password、secret等關(guān)鍵字的properties的值,保護(hù)信息安全) |
/actuator/flyway | GET | 顯示已應(yīng)用的所有Flyway數(shù)據(jù)庫(kù)遷移 |
/actuator/health (常用) | GET | 查看當(dāng)前SpringBoot運(yùn)行的健康指標(biāo),值由HealthIndicator的實(shí)現(xiàn)類提供(所以可以自定義一些健康指標(biāo)信息) |
/actuator/heapdump | GET | 會(huì)自動(dòng)生成一個(gè)JVM的堆文件 |
/actuator/info | GET | 展示了關(guān)于應(yīng)用的一般信息,這些信息從編譯文件比如META-INF/build-info.properties或者Git文件比如git.properties或者任何環(huán)境的property中獲取。 |
/actuator/mappings | GET | 查看全部的endpoint(包含 Actuator 的),即路徑列表 |
/actuator/metrics(常用) | GET | 查看有哪些指標(biāo)可以看(ex: jvm.memory.max、system.cpu.usage),使用/actuator/metrics/{metric.name}可以查看各指標(biāo)的詳細(xì)信息 |
/actuator/scheduledtasks | GET | 查看定時(shí)任務(wù)的信息 |
/actuator/shutdown | POST | 唯一一個(gè)需要POST請(qǐng)求的endpoint,使應(yīng)用程序正常關(guān)閉 |
更多詳細(xì)的EndPoint可以查看:Spring Boot Actuator [監(jiān)控與管理]
集成 Actuator
創(chuàng)建示例項(xiàng)目
我們先創(chuàng)建一個(gè)demo應(yīng)用,可以通過(guò)Spring Initializr創(chuàng)建:
引入依賴
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Gradle
dependencies {
compile("org.springframework.boot:spring-boot-starter-actuator")
}
端點(diǎn)配置
默認(rèn)暴露端點(diǎn)
我們可以通過(guò)以下配置,來(lái)配置通過(guò)JMX 和 HTTP 暴露的端點(diǎn)。
Property | Default |
---|---|
management.endpoints.jmx.exposure.exclude | |
management.endpoints.jmx.exposure.include | * |
management.endpoints.web.exposure.exclude | |
management.endpoints.web.exposure.include | info, health |
考慮到安全因素,Actuator默認(rèn)只開放了/actuator/health
和/actuator/info
這兩個(gè)endpoint,如果要開放其他endpoint,需要額外在application.properties中進(jìn)行設(shè)置。
暴露配置
① 打開所有的監(jiān)控點(diǎn)
management:
endpoints:
enabled-by-default: true #暴露所有端點(diǎn)信息
web:
exposure:
include: '*' #以web方式暴露(不包含shutdown)
② 開放指定的endpoint
management:
endpoints:
enabled-by-default: true #暴露所有端點(diǎn)信息
web:
exposure:
include: beans,mappings # 如果指定多個(gè)端點(diǎn),用","分開
③ 關(guān)閉指定的endpoint
management:
endpoints:
web:
exposure:
exclude: beans# 如果指定多個(gè)端點(diǎn),用","分開
include: *
exclude通常會(huì)跟include一起用,就是先include了全部,然后再exclude/actuator/beans
這個(gè)endpoint。
④ 開放shutdown,需額外配置
management:
endpoints:
shutdown:
enabled: true
路徑配置
① 默認(rèn)情況下所有端點(diǎn)都暴露在/actuator
路徑下,也可以改變/actuator
的路徑,可以自定義:
management:
endpoints:
web:
base-path: /monitor
設(shè)置完重啟后,原本內(nèi)建的/actuator/xxx
路徑,都會(huì)變成/monitor/xxx
,可以用來(lái)防止被其他人猜到。
② 支持單個(gè)endpoint路徑定義,比如將health修改成healthcheck
management:
endpoints:
web:
path-mapping:
health: healthcheck
管理端口調(diào)整
management:
server:
port: 11011
自定義端口,默認(rèn)跟server.port
一樣,可以防止被其他人猜到
端點(diǎn)響應(yīng)緩存
對(duì)于一些不帶參數(shù)的端點(diǎn)請(qǐng)求會(huì)自動(dòng)進(jìn)行緩存,我們可以通過(guò)如下方式配置緩存時(shí)間,下面配置表示 beans端點(diǎn)的緩存時(shí)間為100s
management:
endpoint:
beans:
cache:
time-to-live: 100s
端點(diǎn)保護(hù)
如果開啟了Actuator默認(rèn)不開放的endpoints,建議一定要加上Spring Security
用于endpoint保護(hù),避免重要信息泄露,必須防止未經(jīng)授權(quán)的外部訪問(wèn)。
這里我們使用Spring Security
保護(hù),首先添加相關(guān)依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
添加之后,我們需要定義安全校驗(yàn)規(guī)則,來(lái)覆蓋Spring Security
的默認(rèn)配置。
這里給出兩個(gè)版本的模板配置:
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
/*
* version1:
* 1. 限制 '/shutdown'端點(diǎn)的訪問(wèn),只允許ACTUATOR訪問(wèn)
* 2. 允許外部訪問(wèn)其他的端點(diǎn)
* 3. 允許外部訪問(wèn)靜態(tài)資源
* 4. 允許外部訪問(wèn) '/'
* 5. 其他的訪問(wèn)需要被校驗(yàn)
* version2:
* 1. 限制所有端點(diǎn)的訪問(wèn),只允許ACTUATOR訪問(wèn)
* 2. 允許外部訪問(wèn)靜態(tài)資源
* 3. 允許外部訪問(wèn) '/'
* 4. 其他的訪問(wèn)需要被校驗(yàn)
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// version1
// http
// .authorizeRequests()
// .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
// .hasRole("ADMIN")
// .requestMatchers(EndpointRequest.toAnyEndpoint())
// .permitAll()
// .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
// .permitAll()
// .antMatchers("/")
// .permitAll()
// .antMatchers("/**")
// .authenticated()
// .and()
// .httpBasic();
// version2
http
.authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint())
.hasRole("ADMIN")
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()
.antMatchers("/")
.permitAll()
.antMatchers("/**")
.authenticated()
.and()
.httpBasic();
}
}
application.properties
的相關(guān)配置如下:
# Spring Security Default user name and password
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ADMIN
我們使用瀏覽器訪問(wèn)http://localhost:8080/actuator/health
端點(diǎn)接口,會(huì)先彈出個(gè)登錄框,只有登錄后才能訪問(wèn)。
定制Endpoint
定制化health信息
① 配置Health顯示情況,詳細(xì)界面顯示配置
management:
health:
enabled: true
show-details: always #總是顯示詳細(xì)信息??娠@示每個(gè)模塊的狀態(tài)信息
② 定制Health Endpoint
添加信息:
1)繼承 AbstractHealthIndicator 類
2)定義參數(shù) Health.Builder builder
3)向參數(shù) builder 中添加狀態(tài)及相關(guān)信息
@Component
//類名截去HealthIndicator后,為顯示時(shí)的組件名
public class MyComHealthIndicator extends AbstractHealthIndicator {
//真實(shí)的檢查方法
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
// 獲取鏈接進(jìn)行測(cè)試
Map<String, Object> map = new HashMap<>();
//檢查完成
if (1 == 1) {
//健康
builder.status(Status.UP);
map.put("count", 1);
} else {
//不健康
builder.status(Status.OUT_OF_SERVICE);
map.put("err", "連接超時(shí)");
map.put("time", 3000);
}
builder.withDetail("code", 100)
.withDetails(map);
}
}
定制info信息
編寫InfoContributor
1)繼承 public class ExampleInfoContributor implements InfoContributor
2)定義 Info.Builder builder 參數(shù)
3)向builder中添加參數(shù)信息
@Component
public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("msg", "你好")
.withDetail("hello", "uclass")
.withDetails(Collections.singletonMap("key", "value"));
}
}
定制Metrics信息
① 利用service層構(gòu)造器,在注冊(cè)中心中添加cityService.saveCity.count指標(biāo)
@Service
public class CityServiceImpl implements CityServices {
@Autowired
CityMapper cityMapper;
Counter counter;
//利用構(gòu)造器,在注冊(cè)中心中添加cityService.saveCity.count指標(biāo)
public CityServiceImpl(MeterRegistry meterRegistry) {
//指標(biāo)中心注冊(cè)新的指標(biāo)項(xiàng)
counter = meterRegistry.counter("cityService.saveCity.count");
}
public void saveCity(City city) {
counter.increment();
cityMapper.insertCity(city);
}
}
② 在配置類中新建配置,添加指標(biāo)
@ServletComponentScan(basePackages = "com.uclass.thymeleaf")
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Bean
MeterBinder queueSize(Queue queue) {
return (registry) -> Gauge.builder("queueSize", queue::size).register(registry);
}
}
//利用構(gòu)造器,在注冊(cè)中心中添加cityService.saveCity.count指標(biāo)
public CityServiceImpl(MeterRegistry meterRegistry) {
//指標(biāo)中心注冊(cè)新的指標(biāo)項(xiàng)
counter = meterRegistry.counter("cityService.saveCity.count");
}
自定義新端點(diǎn)
利用 @Endpoint(id = “myservice”) 注解文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-732879.html
- id屬性代表新增的端點(diǎn)名稱
- 利用@ReadOperation、@WritOperation注解,在端點(diǎn)中添加信息
@Component
@Endpoint(id = "myservice")
public class MyServiceEndPoint {
@ReadOperation
public Map getDockerInfo () {
//端點(diǎn)的讀操作
return Collections.singletonMap("dockerInfo", "docker start...");
}
@WriteOperation
private void restartDocker(){
System.out.println("docker restarted....");
}
}
參考資料
SpringBoot 指標(biāo)監(jiān)控——Actuator
Spring boot——Actuator 詳解文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-732879.html
到了這里,關(guān)于Spring Boot Actuator詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!