SpringBoot项目端点配置

一、端点配置

1.pom依赖

在SpringBoot中开启应用监控非常容易,只需要添加spring-boot-starter-actuator依赖即可,actuator(执行器)是制造业术语,指一个用于移动或控制机械装置的工具,一个很小的变化就能让执行器产生大量的运动。

依赖如下:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.端点列表

开发者可以使用执行器中的端点(EndPoints)对应用进行监控或者与应用进行交互,SpringBoot默认包含许多端点,如下表:

端点 端点描述 是否开启
auditevents 展示当前应用程序的审计信息(要配置特定的bean) Yes
beans 展示所有SpringBeans信息 Yes
conditions 展示一个自动配置类的使用报告,该报告展示所有自动配置类及他们被使用或未使用的原因(在配置文件中开启debug: true也可以看到条件) Yes
configprops 展示所有@configurationProperties的列表 Yes
env 展示系统运行信息 Yes
flyway 展示数据库迁移路径 Yes
health 展示应用程序的健康信息 Yes
httptrace 展示trace信息,(默认为最新的100条HTTP请求)(要配置特定的bean) Yes
info 展示应用的定制信息,这些定制信息以info开头 Yes
loggers 展示并修改应用的日志配置 Yes
liquibase 展示任何Liquibase数据库迁移路径 Yes
metrice 展示应用程序度量信息 Yes
mappings 展示所有@RequestMapping路径的集合列表 Yes
scheduledtasks 展示应用的所有定时任务 Yes
shutdown 远程关闭应用接口 No
sessions 展示并操作spring session回话 Yes
threaddump 展示线程活动的快照 Yes

如果是个Web应用,还会有下面的端点:

端点 端点描述 是否开启
headdump 返回一个GZip压缩的hprof堆转储文件 Yes
jolokia 展示通过HTTP暴露的JMX beans Yes
logfile 返回日志文件的内容 Yes
prometheus 展示一个可以被Promentheus服务器抓取的metrics数据 Yes

这些端点大部分都是默认开启的,只有shutdown端点默认关闭的,如果需要开启,可以在application.yml中通过如下配置开启:

# 开启远程关闭应用接口(风险操作)
management:
  endpoint:
    shutdown:
      enabled: true

3.暴露端点

由于有的端点包含系统的铭感信息,端点启用和暴露是两码事。下表展示了端点的默认暴露情况。

端点 JMX Web
auditevents Yes NO
beans Yes NO
conditions Yes NO
configprops Yes NO
env Yes NO
flyway Yes NO
health Yes Yes
httptrace Yes NO
info Yes Yes
loggers Yes NO
liquibase Yes NO
metrics Yes NO
mapping Yes NO
scheduledtasks Yes NO
shutdown Yes NO
sessions Yes NO
threaddump Yes NO
headdump N/Y NO
jolokia N/Y NO
logfile N/Y NO
prometheus N/Y NO

在Web应用中,默认只有healthinfo两个端点暴露,即当开发者在SpringBoot项目中加入spring-boot-starter-actuator依赖并启动SpringBoot项目后,默认只有这两个端口可访问。

开发者可以在配置文件中自定义需要暴露哪些端点,例如要暴露mappingmetrics端点,添加如下配置即可:

management:
  endpoints:
    web:
      exposure:
        include: mapping,metrics

暴露所有端点,添加如下配置

management:
  endpoints:
    web:
      exposure:
        include: "*"

4.端点保护

如果这些端点需要对外提供服务,那么最好能够讲这些端点保护起来,若classpath中存在SpringSecurity,则默认使用SpringSecurity保护,使用SpringSecurity保护的步骤很简单,首先添加SpringSecurity依赖:

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

然后添加SpringSecurity配置,代码如下:

@Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(EndpointRequest.toAnyEndpoint())
                .authorizeRequests()
                .anyRequest().hasRole("ADMIN")
                .and()
                .httpBasic();
    }
}

在HttpSecurity中配置所有的Endpoint多需要具有ADMIN角色才能访问,同时开启httpBasic认证。

注意,EndpointRequest.toAnyEndpoint()表示匹配所有的Endpoint,例如:shutdown、mappings、health等,但不包括开发者通过@RequestMapping注解定义的接口。

添加配置

spring:
  security:
    user:
      name: 用户名
      password: 密码
      roles: ADMIN

定义完成后,再去访问health端点,需要登录后才可以访问。

5.端点响应缓存

对于不带参数的端点请求,会自动进行缓存,开发者可通过如下方式配置缓存时间:

management:
  endpoint:
    beans:
      cache:
        time-to-live: 100s

这个配置表示beans端点的缓存时间为100s,如果要配置其他的端点,只需将beans修改为其他的端点名即可。

注意:如果端点添加了SpringSecurity保护,此时Principal会被视为端点的输入,因此端点响应将不被缓存。

6.路径映射

默认情况下,所有的端点都暴露在“/actuator”路径下,例如health端点的访问路径是“/actuator/health”,如果开发者需要对端点路径进行定制,可通过如下配置进行:

management:
  endpoints:
    web:
      base-path: /
      path-mapping: 
        health: healthcheck

修改后health端点的访问路径由“/actuator/health”变为“/healthcheck”。

7.CORS支持

所有端点默认都没有开启跨域,开发者可以通过如下配置,快速开启CORS支持,进而实现跨域:

management:
  endpoints:
    web:
      cors:
        allowed-origins: http://localhost:8080
        allowed-methods: GET,POST

二、健康信息

1. 展示健康信息详情

开发者可以通过查看健康信息来获取应用的运行数据,进而提早发现应用问题,提早解决,避免造成损失。默认情况下这只能获取到status信息,这是因为detail信息默认不显示,
开发者可以通过management.endpoint.health.show-detail属性来配置detail信息的显示策略,该属性的取值有三种:

  • never:即不显示detail信息,默认即此

  • when-authorized:detail信息只展示给认证用户,即用户登录后可查看detail信息,未登录则不可查看,另外可以通过management.endpoint.health.roles属性配置要求的角色,
    如果不配置,那么通过认证的用户都可以查看detail信息,如果配置了,例如management.endpoint.health.roles=ADMIN表示认证的用户必须具有ADMIN角色才能查看detail信息。

  • always:将detail信息展示给所有用户。

例如:在pom.xml文件中加入SpringSecurity依赖后,在application.yml文件中增加如下配置:

management:
  endpoint:
    health:
      show-details: when_authorized
      roles: ADMIN
  endpoints:
    web:
      exposure:
        include: "*"
spring:
  security:
    user:
      name: yulu
      password: 123
      roles: ADMIN

这里首先暴露所有端点,配置health的detail信息只展示给认证用户,并且认证用户还要具有ADMIN角色,然后配置一个默认用户,用户名是yulu 密码是123,用户角色是ADMIN。

配置完成后,启动SpringBoot项目,在Postman中访问health端点,如下图所示:

在这里插入图片描述

2. 健康指示器

SpringBoot会根据classpath中依赖的添加情况来自动配置一些HealthIndicators,如下表所示:

名字 描述
CassandraHealthIndicator 检查Cassandra数据库状况
DiskSpaceHealthIndicator 低磁盘空间检查
DataSourceHealthIndicator 检查是否可以从DataSource获取一个Connection
ElasticsearchHealthIndicator 检查Elasticsearch集群状况
InfluxDbHealthIndicator 检查InfluxDB状况
JmsHealthIndicator 检查JMS消息代理状况
MailHealthIndicator 检查邮件服务器状况
MongoHealthIndicator 检查MongoDB数据库状况
Neo4jHealthIndicator 检查Neo4j服务器状况
RabbitHealthIndicator 检查Rabbit服务器状况
RedisHealthIndicator 检查Redis服务器状况
SolrHealthIndicator 检查Solr服务器状况

如果项目中存在相关的依赖,那么列表中对应的HealthIndicators将会被自动配置。

若开发者不需要这么多的HealthIndicators,则可以通过如下配置关闭所有的HealthIndicators自动化配置:

management:
  health:
    defaults:
      enabled: false

3. 自定义HealthInfo

除了SpringBoot自动收集的这些HealthInfo之外,开发者也可以自定义HealthInfo,实现HealthIndicator接口即可:

@Component
public class MyHealth implements HealthIndicator {
    @Override
    public Health health() {
        if (checkNetWork()){
            return Health.up().withDetail("msg","网络连接正常。。。").build();
        }
        return Health.up().withDetail("msg","网络断开。。。").build();
    }
    private static boolean checkNetWork(){
        return true;
    }
}

代码解释:

开发者自定义类实现HealthIndicator接口,并实现接口中的health方法,在health方法中,checkNetWork是一个网络连接检查的方法,Health中的up的down方法分别对应两种常见的响应状态,即“up”和“down”。

默认的响应状态一共有4种,定义在OrderedHealthAggregator类中,分别是DOWN、OUT_OF_SERVICE、UP、UNKNOWN,如果想增加响应状态,
可以自定义了继承自OrderedHealthAggregator,或者在application.yml中通过management.health.status.order属性进行配置。

如果开发者想要增加响应状态FATAL,在application.yml中增加如下配置即可:

management:
  health:
    status:
      order: FATAL,DOWN,OUT_OF_SERVICE,UP,UNKNOWN

配置完成后,就可以在health方法中返回自定义的响应状态了,修改MyHealth的health方法如下:

@Component
public class MyHealth implements HealthIndicator {
    @Override
    public Health health() {
        return Health.status("FATAL").withDetail("msg","网络断开。。。").build();
    }
}

三、应用信息

应用信息就是通过/actuator/info接口获取到的信息

主要包含三大类:自定义信息、Git信息以及项目构建信息

1. 自定义信息

自定义信息可以在配置文件中添加,也可以在Java代码中添加。

在配置文件中添加是指在application.yml中手动定义info信息,这些信息将在info端点中显示出来,例如在application.yml中配置如下信息:

info: 
  app: 
    encoding: @project.build.sourceEncoding@
    java: 
      source: @java.version@
      target: @java.version@
  author: 
    name: yulu
    email: aaa@163.com

注意@...xxx...@表示引用Maven中的定义

添加这些配置信息之后,重启SPringBoot项目,访问/actuator/info端点,结果如下图所示:

在这里插入图片描述

@Component
public class MyInfo implements InfoContributor {
    @Override
    public void contribute(Info.Builder builder) {
        Map<String,Object> info = new HashMap<>();
        info.put("name","yulu1");
        info.put("email","bbb@123.com");
        builder.withDetail("author",info);
    }
}

此时访问info端点,结果如下图所示:

在这里插入图片描述

2.项目构建信息

  如果classpath下存在META-INF/build-info.properties文件,SpringBoot项目将自动构建BuildPropertiesBean,
然后info端点会发布build-info.properties文件中的信息。build-info.properties文件可以通过插件自动生成,具体操作步骤如下:

首先在pom.xml文件中添加插件:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>build-info</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <excludes>
            <exclude>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </exclude>
        </excludes>
    </configuration>
</plugin>

然后在IDEA中单击MavenProject,找到该插件,单击spring-boot:build-info按钮,生成构建信息。如下图所示:

在这里插入图片描述

构建信息生成成功后,在项目目录下的target/classes/META-INF目录下生成了一个build-info.properties文件,内容如下图所示:

build.artifact=chapter14-1
build.group=com.demo
build.name=chapter14-1
build.time=2021-03-22T11\:19\:23.967Z
build.version=0.0.1-SNAPSHOT

此时启动SpringBoot项目,访问info端点,构建信息将被自动发布。

四、使用admin监控

可以参考若依框架的配置

<!-- 监控端依赖 -->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>

<!-- 被监控端依赖 -->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
</dependency>

五、参考文章

https://blog.csdn.net/yulu32/article/details/115093675

posted @ 2022-05-27 10:21  黄河大道东  阅读(324)  评论(0编辑  收藏  举报