我使用SpringBootAdmin来监视我的springboot应用程序,它非常好。但我需要先启动SpringBoot管理服务器,然后启动包含SpringBoot客户端的应用程序。
有没有办法将Spring Boot服务器包含到我的Spring Boot应用程序中,使它们看起来像一个应用程序,这样我就可以启动我的应用程序,然后服务器启动,客户端注册到服务器。最终目的是我的应用程序在端口8080上运行,而spring boot admin在端口8081上运行。
我已经检查了这个线程:如何在同一个应用程序中运行SpringBootAdmin客户端和服务器,但它不包含任何细节,我无法用可能的解决方案实现。
PS:我知道我可以打包spring boot管理服务器,然后编写开始代码。先启动服务器,然后启动我的应用程序,但这不是一个很好的解决方案。
有人能帮忙吗?
SpringBoot版本:2.3.4。发布Spring启动管理版本:2.3.0
探索spring多模块特性以解决您的用例。
将Spring Boot服务器作为父项目,并将所有Spring Boot客户端项目添加为单个模块。所有这些单独的模块都只是一个Spring Boot应用程序。您可以在任何不同的端口上打包和部署这些单独的模块。
一个更简单的解决方案是让应用程序在容器中运行,最好将它们隔离,而不是将它们变成一个整体。
您可以使用docker构建应用程序(https://spring.io/guides/gs/spring-boot-docker/)
基本上,每个应用程序都有一个docker文件,如下所示:
FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
并使用docker compose启动它们
version: '3.7'
services:
spring-boot-admin:
image: spring-boot-admin-image
container_name: spring-boot-admin
ports:
- 8081:8081
healthcheck:
test: "curl --fail --silent localhost:8081/actuator/health | grep UP || exit 1"
interval: 20s
timeout: 5s
retries: 5
start_period: 40s
spring-boot-client:
image: spring-boot-client-image
container_name: spring-boot-client
ports:
- 8080:8080
depends_on:
- spring-boot-admin
Dependes_on将确保您的spring boot客户端在spring boot admin运行正常后启动
从技术上讲,这应该可以将两者集成到一个应用程序中,但恐怕您很快就会遇到问题。
但是让我们试试看。。。
参考:概念证明GitHub
这种方法的问题:
8080
上的客户端,端口8081上的管理服务器
我们可以使用配置文件
来分离多个配置文件,以便利用特定于配置文件的文件
应用程序客户端。性质
server.address=localhost
spring.boot.admin.client.url = http://localhost:8081/
management.endpoints.web.exposure.include = *
management.endpoint.health.show-details= always
spring.application.name=client-app
spring.boot.admin.client.instance.name=client-app
application-admin.properties
server.address=localhost
server.port=8081
人口应用
public class DemoApplication {
public static void main(String[] args) throws Exception {
SpringApplication admin = new SpringApplication(DemoAdminServer.class);
admin.setAdditionalProfiles("admin");
admin.run(args);
SpringApplication client = new SpringApplication(DemoClient.class);
client.setAdditionalProfiles("client");
client.run(args);
}
}
@EnableAdminServer
@Configuration
@EnableAutoConfiguration
@Profile("admin")
class DemoAdminServer {
}
@SpringBootApplication
@RestController
@Profile("client")
class DemoClient {
@GetMapping
public String hello(){
return "Hello world!";
}
}
启动应用程序,我们应该很好。。。
如果您有两个独立的应用程序,那么在客户端
中,您可以通过一个进程启动管理服务器
。
@SpringBootApplication
public class ClientApplication {
public static void main(String[] args) throws Exception{
startAdminServer();
SpringApplication.run(DemoApplication.class, args);
}
static void startAdminServer() throws Exception {
new ProcessBuilder()
.redirectErrorStream(true)
.command("cmd.exe",
"/c",
"java -jar path_to_your_admin_server.jar")
.start();
}
}