如何在同一Spring Boot Web应用中同时集成Spring Boot Admin Server与Client
没问题,把Spring Boot Admin Server和Client集成到同一个Web应用里其实挺简单的,我一步步给你拆解操作步骤:
首先你需要同时引入Spring Boot Admin Server和Client的starter依赖,因为你的应用要同时扮演管理端和被管理端的角色。
如果用Maven,在pom.xml里添加这两个依赖(注意版本要和你的Spring Boot版本匹配:Spring Boot 3对应Spring Boot Admin 3.x,Spring Boot 2对应2.x):
<dependencies> <!-- Spring Boot Admin Server --> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-server</artifactId> <version>3.2.3</version> <!-- 替换成对应你的Spring Boot版本的Admin版本 --> </dependency> <!-- Spring Boot Admin Client --> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> <version>3.2.3</version> </dependency> <!-- 你的Spring Web依赖已经有了,这里不用重复加 --> </dependencies>
如果用Gradle,在build.gradle里添加:
dependencies { implementation 'de.codecentric:spring-boot-admin-starter-server:3.2.3' implementation 'de.codecentric:spring-boot-admin-starter-client:3.2.3' implementation 'org.springframework.boot:spring-boot-starter-web' }
在你的Spring Boot启动类上添加@EnableAdminServer注解,这样就能开启Admin Server的核心功能:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import de.codecentric.boot.admin.server.config.EnableAdminServer; @SpringBootApplication @EnableAdminServer // 加上这个注解开启Admin Server public class EventsGeneratorApplication { public static void main(String[] args) { SpringApplication.run(EventsGeneratorApplication.class, args); } }
你现有的配置需要做一点修改,因为Client要注册到自己的Server上:
打开你的application.properties,修改并补充以下配置:
# 原配置里的url指向了8080,但你的应用端口是8081,改成自己的服务地址 spring.boot.admin.client.url=http://localhost:8081 # 新增这个配置,确保Client能正确上报自身服务地址,避免自动检测出现异常 spring.boot.admin.client.instance.service-base-url=http://localhost:8081 # 你原来的这些配置已经符合要求,保留即可 spring.application.name=Events generator management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always server.port=8081
现在启动你的应用,访问http://localhost:8081,就能看到Spring Boot Admin的管理界面了。在界面的实例列表里,你应该能看到名为"Events generator"的应用已经成功注册,点击进去就能查看各种监控指标、端点状态等信息。
额外注意事项
如果你的应用启用了Spring Security,可能需要额外配置来允许Admin Server和Client之间的通信,比如开放Actuator端点的访问权限,或者设置Admin的登录凭证(如果开启了安全验证)。不过如果没用到Security的话,上面的步骤就足够完成集成了。
内容的提问来源于stack exchange,提问作者Pikappa

