地址
问题背景
如何在一套系统系统中开启多个端口面向不同服务对象
当然,这里说的不是 springboot 多个监听端口的启动,而是在一套其他启动多个 springboot,分别运行在不同端口,各自有不同的逻辑
介绍
下面我们来看org.springframework.boot.builder
中的SpringApplicationBuilder
,这里为我们提供了这种实现方法
Builder for SpringApplication and ApplicationContext instances with convenient fluent API and context hierarchy support. Simple example of a context hierarchy:
new SpringApplicationBuilder(ParentConfig.class).child(ChildConfig.class).run(args);Another common use case is setting active profiles and default properties to set up the environment for an application:
new SpringApplicationBuilder(Application.class).profiles(“server”)
.properties(“transport=local”).run(args);If your needs are simpler, consider using the static convenience methods in SpringApplication instead.
SpringApplication 和 ApplicationContext 实例的构建器,具有便利的流利的 API 和上下文层次结构支持。 上下文层次结构的简单示例
这样的多启动器是具有上下文的,可以定义一个无 web 的父 springboot,以及多个子 springboot
比如
启动器配置
fun main(args: Array<String>) {
SpringApplicationBuilder()
.parent(CoreApplication::class.java).web(WebApplicationType.NONE)
.child(WebApplication::class.java).web(WebApplicationType.SERVLET)
.sibling(WorkApplication::class.java).web(WebApplicationType.SERVLET)
.run(*args)
}
WebApplicationType
是一个枚举类,有三个可选项
/**
* An enumeration of possible types of web application.
*
* @author Andy Wilkinson
* @author Brian Clozel
* @since 2.0.0
*/
public enum WebApplicationType {
/**
* The application should not run as a web application and should not start an
* embedded web server.
* 该应用程序不应作为Web应用程序运行,也不应启动嵌入式Web服务器。
*/
NONE,
/**
* The application should run as a servlet-based web application and should start an
* embedded servlet web server.
* 该应用程序应作为基于Servlet的Web应用程序运行,并应启动嵌入式Servlet Web服务器
*/
SERVLET,
/**
* The application should run as a reactive web application and should start an
* embedded reactive web server.
* 该应用程序应作为反应式Web应用程序运行,并应启动嵌入式反应式Web服务器。
*/
REACTIVE;
....
}
多个 SpringApplication 实例
CoreApplication 父
@Configuration
@ComponentScan("com.xx.xx.core","com.xx.xx.common")
@EnableCaching
@EnableAutoConfiguration
@EnableTransactionManagement
@EnableScheduling
class CoreApplication
WebApplication(子 1)
@EnableCaching
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.xxx.xxx.web")
@PropertySource("classpath:application-web.properties")
// Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
// @ServletComponentScan
class WebApplication
application-web.properties
server.port=8080
WorkApplication(子 2)
@Configuration
@EnableCaching // 缓存
@EnableScheduling // 定时任务
@ComponentScan("com.xxx.xxx.work")
@EnableAutoConfiguration
@PropertySource("classpath:application-work.properties")
class WorkApplication
application-work.properties
server.port=12563
文件结构图
-
项目结构图
-
配置文件结构图
两个子 SpringApplication 是同级关系,继承于主的yml
配置