我在一个应用程序中有2 个主要入口点。
第一个 main启动服务器,映射控制器并启动一些工作线程。这些工作人员从云队列接收消息。
如果负载增加,我希望能够增加额外的工人来完成我的工作。因此,我的应用程序中有第二个 Main入口点,我希望能够在不启动 spring-boot 中的默认服务器(作为客户端应用程序)的情况下启动它,以避免端口冲突(显然这会导致失败)。
我如何实现这一目标?
我在一个应用程序中有2 个主要入口点。
第一个 main启动服务器,映射控制器并启动一些工作线程。这些工作人员从云队列接收消息。
如果负载增加,我希望能够增加额外的工人来完成我的工作。因此,我的应用程序中有第二个 Main入口点,我希望能够在不启动 spring-boot 中的默认服务器(作为客户端应用程序)的情况下启动它,以避免端口冲突(显然这会导致失败)。
我如何实现这一目标?
server
使用和client
配置文件从命令行启动要将相同的 jar 和相同的入口点与 2 个不同的配置文件一起使用,您应该简单地在运行时提供 Spring 配置文件,以加载不同的 application-${profile}.properties(并可能触发条件 Java 配置)。
定义 2 个弹簧轮廓 (client
和server
):
application-${profile}.properties
有一个 SpringBootApp 和入口点:
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.run(args);
}
}
让这门课成为你的主课。
src/main/resources/ application-server.properties:
spring.application.name=server
server.port=8080
src/main/resources/ application-client.properties:
spring.application.name=client
spring.main.web-environment=false
从命令行启动两个配置文件:
$ java -jar -Dspring.profiles.active=server YourApp.jar
$ java -jar -Dspring.profiles.active=client YourApp.jar
您也可以@Configuration
根据活动配置文件有条件地触发类:
@Configuration
@Profile("client")
public class ClientConfig {
//...
}
server
使用和client
配置文件从 IDE 启动发射器:
@SpringBootApplication
public class SpringBootApp {
}
public class LauncherServer {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.profiles("server")
.run(args);
}
}
public class ClientLauncher {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.profiles("client")
.web(false)
.run(args);
}
}
您可以指定其他配置类(特定于客户端或服务器):
new SpringApplicationBuilder()
.sources(SpringBootApp.class, ClientSpecificConfiguration.class)
.profiles("client")
.web(false)
.run(args);
src/main/resources/ application-server.properties:
spring.application.name=server
server.port=8080
src/main/resources/ application-client.properties:
spring.application.name=client
#server.port= in my example, the client is not a webapp
请注意,您可能还有 2 个 SpringBootApp (
ClientSpringBootApp
,ServerSpringBootApp
),每个都有自己的 main,这是一个类似的设置,允许您配置不同的AutoConfiguration
或ComponentScan
:
@SpringBootApplication
@ComponentScan("...")
public class ServerSpringBootApp {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(ServerSpringBootApp.class)
.profiles("server")
.run(args);
}
}
//Example of a difference between client and server
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@ComponentScan("...")
public class ClientSpringBootApp {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(ClientSpringBootApp.class)
.profiles("client")
.web(false)
.run(args);
}
}