如何不依赖spring-boot-starter-web使用spring-boot-starter-actuator实现健康检查与Prometheus指标
解决方案:无需Spring Web Starter暴露Actuator HTTP端点
1. 添加必要的轻量级依赖
不需要引入spring-boot-starter-web,只需添加以下两个核心依赖到你的构建文件中:
Maven(pom.xml)
<dependencies> <!-- Actuator核心依赖,提供健康检查、指标采集能力 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 轻量级嵌入式Web服务器(替代Spring Web Starter的Tomcat,资源占用更低) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> </dependencies>
Gradle(build.gradle)
dependencies { implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-undertow' }
Undertow是高性能轻量Web服务器,体积和资源占用远小于Tomcat,完全满足承载Actuator端点的需求。
2. 配置Actuator端点暴露
在application.yml或application.properties中配置端点暴露规则及相关参数:
application.yml
management: endpoints: web: exposure: include: health, prometheus # 仅暴露需要的端点,减少不必要的暴露 endpoint: health: show-details: always # 可选,生产环境建议设为`when_authorized`,仅授权用户查看详情 server: port: 8081 # 可选,单独指定Actuator端口,避免与业务服务(gRPC/Stream)端口冲突
application.properties
management.endpoints.web.exposure.include=health,prometheus management.endpoint.health.show-details=always management.server.port=8081
3. 适配业务服务的注意事项
- Spring Cloud Stream服务:Stream基于消息驱动无Web环境,添加Undertow依赖后会自动启动轻量Web容器,专门承载Actuator端点,不会影响Stream的消息处理逻辑。
- Spring gRPC服务:gRPC默认使用Netty作为通信框架,配置独立的
management.server.port后,Actuator会在单独端口启动HTTP服务,完全不会与gRPC默认端口(9090)冲突。
4. Kubernetes配置示例
健康检查(Liveness/Readiness Probe)
livenessProbe: httpGet: path: /actuator/health port: 8081 # 对应配置的management.server.port,未单独指定则用应用端口 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /actuator/health port: 8081 initialDelaySeconds: 5 periodSeconds: 5
Prometheus指标采集
在Prometheus配置中添加Scrape规则:
scrape_configs: - job_name: 'your-service-name' static_configs: - targets: ['your-service:8081'] metrics_path: '/actuator/prometheus'
关键说明
- 该方案仅引入最小必要依赖,避免了
spring-boot-starter-web带来的冗余内容。 - Spring Boot 3.4.3完全兼容上述配置,无需额外兼容处理。
- 若偏好其他轻量Web服务器,可替换
spring-boot-starter-undertow为spring-boot-starter-jetty,两者均可满足需求。
内容的提问来源于stack exchange,提问作者Дима Гуманов
相关产品推荐
相关产品推荐

