多個springboot運行在同一個JVM

概述

當(dāng)下作為Java開發(fā)人員,運行一個服務(wù)基本上都會直接基于springboot,因此啟動N個服務(wù)是需要啟動N個springboot程序的。特別在本地環(huán)境通過intellij運行多個服務(wù)的時候,會需要占用較大的資源,電腦往往會出現(xiàn)卡頓現(xiàn)象。

本文主要介紹如何通過啟動一個(入口) main 方法來運行多個服務(wù),從而提高本地的開發(fā)爽度。

如何運行

本文例子參考于github的地址,文末有提供

創(chuàng)建項目

基本結(jié)構(gòu)

通過 intellij 創(chuàng)建一個項目,并創(chuàng)建如下module

  • launcher
  • common-service
  • first-service
  • second-service

導(dǎo)入必要的依賴

    <dependencyManagement>
        <dependencies>
            <!-- springboot -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <version>${spring.boot.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>${spring.boot.version}</version>
            </dependency>
            <!-- 會引起一個JMX的問題,下文會說明如何解決 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
                <version>${spring.boot.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

單個服務(wù)說明

sbojvm-3-wm-1571537594.jpg

在 first-service 和 second-service 編寫最基本的 web 所需要的類 Application 和 Controller

代碼如下:

@SpringBootApplication
public class FirstApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstApplication.class, args);
    }

}
@RestController
public class FirstController {

    @GetMapping(value = "/index")
    public String index() throws Exception {
        return "Hello from first microservice!";
    }

}
public class FirstServiceBackendRunner extends BackendRunner {

    public FirstServiceBackendRunner() {
        super("first", FirstApplication.class, CustomizationBean.class);
    }

}
// 如果是springboot1.x
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Value( "${backend.apps.first.contextPath}" )
    private String contextPath;

    @Value( "${backend.apps.first.port}" )
    private Integer port;

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setContextPath(contextPath);
        container.setPort(port);
    }

}

// 如果是springboot2.x
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Value( "${backend.apps.first.contextPath}" )
    private String contextPath;

    @Value( "${backend.apps.first.port}" )
    private Integer port;

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.setContextPath(contextPath);
        factory.setPort(port);
    }

}

圖片中的兩個 yml 寫下面一個內(nèi)容即可

spring:
  application:
    name: FirstService
server:
  port: 8110
  servlet:
    contextPath: /first    

運行核心類

在common模塊的核心類

public abstract class BackendRunner {

    // 區(qū)分不通服務(wù)的配置
    private String profile;

    private ConfigurableApplicationContext appContext;
    private final Class<?>[] backendClasses;

    private Object monitor = new Object();
    private boolean shouldWait;

    protected BackendRunner(String profile, final Class<?>... backendClasses) {
        this.backendClasses = backendClasses;
        this.profile = profile;
    }

    public void run() {
        if (appContext != null) {
            throw new IllegalStateException("AppContext must be null to run this backend");
        }
        runBackendInThread();
        waitUntilBackendIsStarted();
    }

    private void waitUntilBackendIsStarted() {
        try {
            synchronized (monitor) {
                if (shouldWait) {
                    monitor.wait();
                }
            }
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    private void runBackendInThread() {
        final Thread runnerThread = new BackendRunnerThread();
        shouldWait = true;
        runnerThread.setContextClassLoader(backendClasses[0].getClassLoader());
        runnerThread.start();
    }

    public void stop() {
        SpringApplication.exit(appContext);
        appContext = null;
    }

    private class BackendRunnerThread extends Thread {
        @Override
        public void run() {
            // 真正啟動
            // 設(shè)置環(huán)境,加載不同配置
            System.setProperty("spring.profiles.active", profile);
            appContext = SpringApplication.run(backendClasses, new String[] {});
            synchronized (monitor) {
                shouldWait = false;
                monitor.notify();
            }
        }
    }

}

啟動核心類

public class MicroservicesStarter {

    private static final List<Backend> activeBackends = new ArrayList<>();

    public MicroservicesStarter() {
    }

    public static void startBackends() throws Exception {
        startBackend("first-software", "com.gongdao.middleware.first.backendRunner.FirstServiceBackendRunner");
        startBackend("second-software", "com.gongdao.middleware.second.backendRunner.SecondServiceBackendRunner");
    }

    /**
     * 啟動入口
     *
     * @param backendProjectName 項目名稱,對應(yīng)文件路徑
     * @param backendClassName   每個服務(wù)的啟動類
     * @throws Exception
     */
    private static void startBackend(final String backendProjectName, final String backendClassName) throws Exception {
        URL runnerUrl = new File(
            System.getProperty("user.dir") + "/" + backendProjectName + "/target/classes/").toURI()
            .toURL();

        URL[] urls = new URL[] {runnerUrl};

        URLClassLoader cl = new URLClassLoader(urls, MicroservicesStarter.class.getClassLoader());
        Class<?> runnerClass = cl.loadClass(backendClassName);

        Object runnerInstance = runnerClass.newInstance();

        final Backend backend = new Backend(runnerClass, runnerInstance);
        activeBackends.add(backend);

        runnerClass.getMethod("run").invoke(runnerInstance);
    }

    public static void stopAllBackends()
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        for (Backend b : activeBackends) {
            b.runnerClass.getMethod("stop").invoke(b.runnerInstance);
        }
    }

    private static class Backend {
        private Class<?> runnerClass;
        private Object runnerInstance;

        public Backend(final Class<?> runnerClass, final Object runnerInstance) {
            this.runnerClass = runnerClass;
            this.runnerInstance = runnerInstance;
        }
    }

}

啟動

點擊 com.gongdao.middleware.LauncherApplication#main 啟動

public class LauncherApplication {

    public static void main(String[] args) {
        try {
            MicroservicesStarter.startBackends();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
sbojvm-1-wm-1571537591.jpg
sbojvm-2-wm-1571537593.jpg

補(bǔ)充說明

原理

利用了不同的classloader(默認(rèn)類+指定的路徑的class文件)去加載不同的服務(wù)

actuate包的JMX注冊異常

在 springboot1.x 的時候出現(xiàn)

2019-09-27 15:13:11.343 ERROR 51322 --- [       Thread-5] o.s.b.a.e.jmx.EndpointMBeanExporter      : Could not register JmxEndpoint [auditEventsEndpoint]

org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.springframework.boot.actuate.endpoint.jmx.AuditEventsJmxEndpoint@65a39e41] with key 'auditEventsEndpoint'; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Endpoint,name=auditEventsEndpoint
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:628) ~[spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter.registerJmxEndpoints(EndpointMBeanExporter.java:174) [spring-boot-actuator-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter.locateAndRegisterEndpoints(EndpointMBeanExporter.java:162) [spring-boot-actuator-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter.doStart(EndpointMBeanExporter.java:158) [spring-boot-actuator-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter.start(EndpointMBeanExporter.java:337) [spring-boot-actuator-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:173) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:50) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:350) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:149) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:112) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:880) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:146) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) [spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at com.gongdao.middleware.common.BackendRunner$BackendRunnerThread.run(BackendRunner.java:58) [classes/:na]
    ......

通過引入 profile 讓每個服務(wù)調(diào)用自己的配置文件,通過配置如下內(nèi)容解決:

需要在 launcher 的resource下添加對應(yīng)的 yml 文件

spring:
  jmx:
    default-domain: FirstService

endpoints:
  jmx:
    unique-names: true
    domain: FirstService

參考資料

https://github.com/rameez4ever/springboot-demo/tree/master/springboot-multi-service-launcher
https://www.davidtanzer.net/david's%20blog/2015/04/01/running-multiple-spring-boot-apps-in-the-same-jvm.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容