spring-boot-starter-actuator是一个用于暴露自身信息的模块,主要用于监控与管理。
加入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
访问
使用前缀/actuator加上端点ID来访问。例如,在默认情况下,health端点映射到/actuator/health。
虽然大部分端点在默认情况下都是启用状态,但是在Spring Boot应用中,默认只开启info端点和health端点。其余端点都需要通过声明属性来开启
management:
endpoints:
web:
exposure:
include: ["*"] #开启全部端点相关代码
保护HTTP端点
这时我们可以像使用任何其他敏感URL一样注意保护HTTP端点。若存在Spring Security,则默认使用Spring Security的内容协商策略来保护端点。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
在配置文件中为Spring Security设置一个安全用户
spring:
security:
user: # 配置安全用户
name: admin
password: 123456
健康信息
health端点是查看Spring Boot应用程序健康状况的端点,如果没有特殊设置,显示的信息就比较少
可以通过在配置文件中设置management.endpoint.health.show-details来决定health端点的细节信息是否展示。以下为health端点的细节属性。
• never:细节信息详情永远都不展示。
• when-authorized:细节详情只对授权用户显示。
• always:细节详情显示给所有用户。
management:
endpoint:
health:
show-details: always #health端点的细节属性是否展示
健康信息的内容是从HealthIndicators中收集应用程序中定义的所有bean中的上下文信息,其中包含一些自动配置的HealthIndicators,也可以编写自己的健康信息bean。Spring Boot默认会自动配置以下HealthIndicators。
• CassandraHealthIndicator:检查Cassandra数据库是否已启动。
• DiskSpaceHealthIndicator:检查磁盘空间是否不足。
• DataSourceHealthIndicator:检查是否可以获得连接的DataSource。
• ElasticsearchHealthIndicator:检查Elasticsearch集群是否已启动。
• InfluxDbHealthIndicator:检查InfluxDB服务器是否已启动。
• JmsHealthIndicator:检查JMS代理是否已启动。
• MailHealthIndicator:检查邮件服务器是否已启动。
• MongoHealthIndicator:检查Mongo数据库是否已启动。
• Neo4jHealthIndicator:检查Neo4j数据库是否已启动。
• RabbitHealthIndicator:检查Rabbit服务器是否已启动。
• RedisHealthIndicator:检查Redis服务器是否已启动。
• SolrHealthIndicator:检查Solr服务器是否已启动。
自定义健康状况信息
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; /** * 自定义健康状况信息 * @author tl19638 * @date 2020/10/5 */ @Component public class MyHealthIndicator implements HealthIndicator { @Value("${server.port}") private String serverPort; @Override public Health health() { if (!"80".equals(serverPort)) { return Health.down().withDetail("端口不是80", "是" + serverPort).build(); } return Health.up().build(); } }
自定义应用程序信息
info: # 公开自定义info信息
encoding: UTF-8
jdk:
version: 1.8
参考:
官网地址:https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/actuator-api//html/
Spring Boot 2实战之旅-8.1 使用actuator监控