Actuator详解

147 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

访问方式:http://localhost:8080/actuator

可以禁用该页面:management.endpoints.web.discovery.enabled=false

EndPoints(端点)

EndPoints允许访问需要两步:启用(enabled)和公开(exposed),内置了很多可用的端点,并且允许自定义端点。

Endpoint描述JMXWeb
auditeventsExposes audit events information for the current application. Requires an AuditEventRepository bean.
beansDisplays a complete list of all the Spring beans in your application.
cachesExposes available caches.
conditionsShows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match.
configpropsDisplays a collated list of all @ConfigurationProperties.
envExposes properties from Spring’s ConfigurableEnvironment.
flywayShows any Flyway database migrations that have been applied. Requires one or more Flyway beans.
healthShows application health information.
httptraceDisplays HTTP trace information (by default, the last 100 HTTP request-response exchanges). Requires an HttpTraceRepository bean.
infoDisplays arbitrary application info.
integrationgraphShows the Spring Integration graph. Requires a dependency on spring-integration-core.
loggersShows and modifies the configuration of loggers in the application.
liquibaseShows any Liquibase database migrations that have been applied. Requires one or more Liquibase beans.
metricsShows ‘metrics’ information for the current application.
mappingsDisplays a collated list of all @RequestMapping paths.
quartzShows information about Quartz Scheduler jobs.
scheduledtasksDisplays the scheduled tasks in your application.
sessionsAllows retrieval and deletion of user sessions from a Spring Session-backed session store. Requires a Servlet-based web application using Spring Session.
shutdownLets the application be gracefully shutdown. Disabled by default.
startupShows the startup steps data collected by the ApplicationStartup. Requires the SpringApplication to be configured with a BufferingApplicationStartup.
threaddumpPerforms a thread dump.
heapdumpReturns an hprof heap dump file. Requires a HotSpot JVM.N/A
jolokiaExposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux). Requires a dependency on jolokia-core.N/A
logfileReturns the contents of the logfile (if logging.file.name or logging.file.path properties have been set). Supports the use of the HTTP Range header to retrieve part of the log file’s content.N/A
prometheus以Prometheus服务器可以抓取的格式公开度量标准, 依赖 micrometer-registry-prometheus。N/A

启用Endpoints

应用程序包含相关服务,但是不对外公开,禁用后应用程序将不再包含相关服务。

默认所有内置Endpoints都是启用的(除了shutdown以外),修改方式:

# 启动
management.endpoint.shutdown.enabled=true
# 禁用
management.endpoint.shutdown.enabled=false

# 可以把所有Endpoints都禁用,并只启用需要的:
management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=true

公开Endpoints

启用后,需要公开才能访问。

需要对JMX和Web单独配置,使用include(公开)和exclude(不公开)配置。

# 公开/关闭 所有接口
management.endpoints.jmx.exposure.include *
management.endpoints.jmx.exposure.exclude *
# 公开/关闭 health接口
management.endpoints.web.exposure.include health,info
management.endpoints.web.exposure.exclude health,info

exclude优先级比include高

*表示全部,如果使用yaml配置文件,*需要用双引号括起来,如:

management:
  endpoints:
    web:
      exposure:
        include: "*"
        exclude: "env,beans"

开启除env,beans之外的全部Endpoints

安全Http Endpoints

使用Securiy即可,如:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .antMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated();
    }
}

CORS支持

默认CORS的支持是禁用的,当配置了management.endpoints.web.cors.allowed-origins后自动启动。

# 允许来自 https://example.com 的GET和POST调用
management.endpoints.web.cors.allowed-origins=https://example.com
management.endpoints.web.cors.allowed-methods=GET,POST

自定义Endpoint

相关的注解:@Endpoint、@ReadOperation、 @WriteOperation和@DeleteOperation,如下:

@Component //必须是个Bean
@Endpoint(id = "us")//公开的Endpoint访问地址/actuator/us
public class UserService {
    @ReadOperation//允许get请求
    public String get(){
        return this.getClass().getName();
    }

    @WriteOperation//允许post请求
    public String post(){
        return this.getClass().getName();
    }

    @DeleteOperation//允许delete请求
    public String delete(){
        return this.getClass().getName();
    }
}

可以返回任何类型的数据,如String、Set或对象之类的。