Spring Boot项目健康检查与监控,Actuator使用教程

本文介绍了如何在Spring Boot应用中配置Actuator的健康检查接口,自定义endpoint以及创建用户自定义的HealthIndicator和Endpoint。通过配置`management.endpoints.web.base-path`改变默认的API路径,并展示了如何扩展HealthEndpoint监控自定义组件的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先引入包

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

配置文件(yml格式)

management:
  endpoints:
    web:
      base-path: /api 
      #作为默认路径,不配置默认路径为/actuator
  endpoint:
    health:
      show-details: always  
      #显示健康具体信息  默认不会显示详细信息

排坑:

需要注意endpoint和endpoints的区别
endpoints下参数为通用属性,如web下修改path等
endpoint下参数是单个指定endpoint,如health,info等

默认的路径从http://localhost:8080/actuator 开始,为了项目中使用需要自定义路径,使用base-path修改即可

默认health返回如下,因此需要show-details: always 展示详情
在这里插入图片描述

health接口返回

{
	"status": "UP",
	"details": {
		"rabbit": {
			"status": "UP",
			"details": {
				"version": "3.8.16"
			}
		},
		"diskSpace": {
			"status": "UP",
			"details": {
				"total": 255850758144,
				"free": 108782460928,
				"threshold": 10485760
			}
		},
		"redis": {
			"status": "UP",
			"details": {
				"version": "6.2.3"
			}
		},
		"db": {
			"status": "UP",
			"details": {
				"database": "MySQL",
				"hello": 1
			}
		},
		"refreshScope": {
			"status": "UP"
		}
	}
}

访问后返回格式如下,如果项目中包含db,redis,mq等都会显示健康状况,其实看 Spring Boot-actuator 源码,你会发现 HealthEndPoint 提供的信息不仅限于此,org.springframework.boot.actuate.health 包下 你会发现 ElasticsearchHealthIndicator、RedisHealthIndicator、RabbitHealthIndicator 等
也就是 HealthEndPoint 也提供 ES, Redis 等组件的健康信息。

"UP"就是安全健康的,"DOWN"就是有问题了.

常用Endpoint

/health/configprops/trace
应用的健康状态获取应用的配置信息,因为Spring Boot 可能发布时是单独的Jar包,配置文件可能包含其中, 当我们需要检查配置文件时可以使用 ConfigpropsEndPoint 进行查看一些配置是否正确。最近几次的http请求信息

所有endpoint列表如下

ID描述
auditevents公开当前应用程序的审核事件信息。
beans显示应用程序中所有Spring bean的完整列表。
caches暴露可用的缓存。
conditions显示在配置和自动配置类上评估的条件以及它们匹配或不匹配的原因。
configprops显示所有的整理列表@ConfigurationProperties,查看配置属性,包括默认配置
env露出Spring的属性的各种环境变量,后面可跟/{name}查看具体的值
flyway显示已应用的任何Flyway数据库迁移。
health显示应用健康信息,在spring boot2.0以后需要在配置里show-details打开所有健康信息
httptrace显示HTTP跟踪信息(默认情况下,最后100个HTTP请求 - 响应交换),2.0以后需要手动打开
info显示任意应用信息,是在配置文件里自己定义的
integrationgraph显示Spring Integration图。
loggers显示和修改应用程序中记录器的配置。
liquibase显示已应用的任何Liquibase数据库迁移。
metrics显示当前应用程序的“指标”信息,比如内存用量和HTTP请求计数,后可跟/{name}查看具体值
mappings显示所有@RequestMapping路径的整理列表。
scheduledtasks显示应用程序中的计划任务。
sessions允许从Spring Session支持的会话存储中检索和删除用户会话。使用Spring Session对响应式Web应用程序的支持时不可用
shutdown允许应用程序正常关闭。
threaddump执行线程转储。

如果您的应用程序是Web应用程序(Spring MVC,Spring WebFlux或Jersey),则可以使用以下附加端点:

ID描述
heapdump返回hprof堆转储文件。
jolokia通过HTTP公开JMX bean(当Jolokia在类路径上时,不适用于WebFlux)。
logfile返回日志文件的内容(如果已设置logging.file或logging.path属性)。支持使用HTTP Range标头检索部分日志文件的内容。
prometheus可以由Prometheus服务器抓取的格式公开指标。

自定义Indicator 扩展 HealthEndPoint

看源码 其实 磁盘和数据库健康信息就是 DiskSpaceHealthIndicator、DataSourceHealthIndicator 来实现的,当我们对一些我们自定义的组件进行监控时, 我们也可以实现个Indicator :

@Component
public class User implements HealthIndicator {
    /**
     * user监控 访问: http://localhost:8088/health
     *
     * @return 自定义Health监控
     */
    @Override
    public Health health() {

        return new Health.Builder().withDetail("usercount", 10) //自定义监控内容
                .withDetail("userstatus", "up").up().build();
    }
}

这时我们再次访问: http://localhost:8088/health 这时返回的结果如下,包含了我们自定义的 User 健康信息。

{
    "status": "UP",
    "user": {
        "status": "UP",
        "usercount": 10,
        "userstatus": "up"
    },
    "diskSpace": {
        "status": "UP",
        "total": 398458875904,
        "free": 315097989120,
        "threshold": 10485760
    },
    "db": {
        "status": "UP",
        "database": "MySQL",
        "hello": 1
    }
}

自定义EndPoint

@Configuration
public class EndPointAutoConfig {
    @Bean
    public Endpoint<Map<String, Object>> customEndPoint() {
        return new SystemEndPoint();
    }
}

@ConfigurationProperties(prefix="endpoints.customsystem")
public class SystemEndPoint extends AbstractEndpoint<Map<String, Object>> {

    public SystemEndPoint(){
        super("customsystem");
    }
    @Override
    public Map<String, Object> invoke() {
        Map<String,Object> result= new HashMap<>();
        Map<String, String> map = System.getenv();
        result.put("username",map.get("USERNAME"));
        result.put("computername",map.get("COMPUTERNAME"));
        result.put("userdomain",map.get("USERDOMAIN"));
        return result;
    }
}

访问 http://localhost:8088/customsystem 来查看我们自定义的EndPoint ,返回结果如下:

{
    "username": "xxx",
    "userdomain": "DESKTOP-6EAN1H4",
    "computername": "DESKTOP-6EAN1H4"
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值