Spring Boot Actuator:介紹和使用


Spring Boot Actuator提供一系列HTTP端點來暴露項目信息,用來監控和管理項目。在Maven中,可以添加以下依賴:

<!-- Spring boot starter: actuator -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

[注] 在某些包中已經自動綁定了Spring Boot Actuator包,比如一些Cloud包spring-cloud-starter-security,spring-cloud-starter-netflix-eureka-server等,這時候不用再重復添加該依賴。

 

Actuator提供了以下端點,默認除了/shutdown都是Enabled。使用時需要加/actuator前綴,如http://localhost:8080/my-app/actuator/health。

ID Description Enabled by default
auditevents 顯示當前應用程序的審計事件信息 Yes
beans 顯示應用上下文中創建的所有Bean Yes
caches 獲取緩存信息 Yes
conditions 顯示配置類和自動配置類(configuration and auto-configuration classes) 的狀態及它們被應用或未被應用的原因 Yes
configprops 該端點用來獲取應用中配置的屬性信息報告 所有@ConfigurationProperties的集合列表 Yes
env 獲取應用所有可用的環境屬性報告。包括: 環境變量、JVM屬性、應用的配置配置、命令行中的參數 Yes
flyway 顯示數據庫遷移路徑(如果有) Yes
health 顯示應用的健康信息 Yes
httptrace 返回基本的HTTP跟蹤信息。 (默認最多100 HTTP request-response exchanges). Yes
info 返回一些應用自定義的信息,我們可以在application.properties 配置文件中通過info前綴來設置這些屬性:info.app.name=spring-boot-hello Yes
integrationgraph Shows the Spring Integration graph. Yes
loggers Shows and modifies the configuration of loggers in the application. Yes
liquibase Shows any Liquibase database migrations that have been applied. Yes
metrics 返回當前應用的各類重要度量指標,比如:內存信息、線程信息、垃圾回收信息等 Yes
mappings 返回所有Spring MVC的控制器映射關系報告 所有@RequestMapping路徑的集合列表 Yes
scheduledtasks 顯示應用程序中的計划任務 Yes
sessions 允許從Spring會話支持的會話存儲中檢索和刪除(retrieval and deletion) 用戶會話。使用Spring Session對反應性Web應用程序的支持時不可用   Yes
shutdown 允許應用以優雅的方式關閉(默認情況下不啟用) No
threaddump 執行一個線程dump Yes

 

如果使用web應用(Spring MVC, Spring WebFlux, 或者 Jersey),還可以使用以下端點:

ID Description Enabled by default
heapdump 返回一個GZip壓縮的hprof堆dump文件 Yes
jolokia 通過HTTP暴露JMX beans(當Jolokia在類路徑上時,WebFlux不可用) Yes
logfile 返回日志文件內容(如果設置了logging.file或logging.path屬性的話), 支持使用HTTP Range頭接收日志文件內容的部分信息                          Yes
prometheus       以可以被Prometheus服務器抓取的格式顯示metrics信息 Yes

 

如果要啟用/禁用某個端點,可以使用management.endpoint.<id>.enabled屬性:

management:
  endpoint:
    shutdown:
      enabled: true

 

另外可以通過management.endpoints.enabled-by-default來修改全局端口默認配置,比如下面禁用所有端點只啟用info端點:

management:
  endpoints:
    enabled-by-default: false
  endpoint:
    info:
      enabled: true

 

上面是啟用/禁用(enable)某個端點,如果使某個端點暴露(exposure)出來,還需要再配置,默認情況下所有端點在JMX下是全部公開的,在Web下只公開/health和/info兩個端點。下面是默認配置:

Property Default
management.endpoints.jmx.exposure.exclude          - 
management.endpoints.jmx.exposure.include  '*'
management.endpoints.web.exposure.exclude  -                  
management.endpoints.web.exposure.include    info, health                                                             

 

下面的例子是Web下公開所有端點:

management:
  endpoints:
    web:
      exposure:
        include: '*'

 

保護Actuator HTTP端點:

最簡單的方式,就是在pom.xml中添加spring-boot-starter-security。由SpringBoot Security的特性可知,系統會自動給我們創建login/logout page,還有一個user和password,此外系統還會自動給我配置一個ManagementWebSecurityConfigurerAdapter(extends WebSecurityConfigurerAdapter),配置Actuator各個Endpoint的權限。

當然我們也可以自定義一個WebSecurityConfigurerAdapter配置自己的user和authority。

package com.mytools;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //@formatter:off
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.inMemoryAuthentication()
            .withUser("user1").password("{bcrypt}" + encoder.encode("password1")).roles("ADMIN","EUREKA")
            .and()
            .withUser("user2").password("{bcrypt}" + encoder.encode("password2")).roles("EUREKA");
        //@formatter:on
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // comes from ManagementWebSecurityAutoConfiguration and ManagementWebSecurityConfigurerAdapter
        //@formatter:off
        http.authorizeRequests()
                .requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin().and()
            .httpBasic();
        //@formatter:on
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM