SpringBoot项目端点配置

端点配置

开启端点

在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>

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

端点端点描述是否开启
auditevents展示当前应用程序的审计信息Yes
beans展示所有SpringBeans信息Yes
conditions展示一个自动配置类的使用报告,该报告展示所有自动配置类及他们被使用或未使用的原因Yes
configprops展示所有@configurationProperties的列表Yes
env展示系统运行信息Yes
flyway展示数据库迁移路径Yes
health展示应用程序的健康信息Yes
httptrace展示trace信息,(默认为最新的100条HTTP请求)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 beansYes
logfile返回日志文件的内容Yes
prometheus展示一个可以被Promentheus服务器抓取的metrics数据Yes

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

management:
  endpoint:
    shutdown:
      enabled: true

如果开发者不想暴露这么多端点,那么可以关闭默认配置,然后手动指定需要开启那些端点,如下配置表示关闭所有端点,只开启info端点:

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

暴露端点

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

端点JMXWeb
auditeventsYesNO
beansYesNO
conditionsYesNO
configpropsYesNO
envYesNO
flywayYesNO
healthYesNO
httptraceYesNO
infoYesYes
loggersYesNO
liquibaseYesNO
metricsYesNO
mappingYesNO
scheduledtasksYesNO
shutdownYesNO
sessionsYesNO
threaddumpYesNO
headdumpN/YNO
jolokiaN/YNO
logfileN/YNO
prometheusN/YNO

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

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

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

要暴露所有端点,添加如下配置即可:

management:
  endpoints:
    web:
      exposure:
        include: *

端点保护

如果这些端点需要对外提供服务,那么最好能够讲这些端点保护起来,若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: yulu
      password: 123
      roles: ADMIN

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

端点响应缓存

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

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

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

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

路径映射

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

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

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

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

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

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

通过Java代码自定义信息只需要自定义类继承自InfoContributor,然后实现该类中的contribute方法即可,代码如下:

@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按钮,生成构建信息。如下图所示:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-i1PmCIZy-在这里插入图片描述

构建信息生成成功后,在项目目录下的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端点,构建信息将被自动发布。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值