如何防止Spring Boot守护程序/服务器应用程序立即关闭/关闭?

Hen*_*wan 23 java spring daemon spring-boot server

我的Spring Boot应用程序不是Web服务器,但它是使用自定义协议的服务器(在本例中使用Camel).

但Spring Boot在启动后立即停止(优雅地).我该如何防止这种情况?

我希望应用程序在Ctrl + C或编程时停止.

@CompileStatic
@Configuration
class CamelConfig {

    @Bean
    CamelContextFactoryBean camelContext() {
        final camelContextFactory = new CamelContextFactoryBean()
        camelContextFactory.id = 'camelContext'
        camelContextFactory
    }

}
Run Code Online (Sandbox Code Playgroud)

Hen*_*wan 27

我找到了解决方案,使用org.springframework.boot.CommandLineRunner+ Thread.currentThread().join(),例如:(注意:下面的代码是在Groovy中,而不是Java)

package id.ac.itb.lumen.social

import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class LumenSocialApplication implements CommandLineRunner {

    private static final log = LoggerFactory.getLogger(LumenSocialApplication.class)

    static void main(String[] args) {
        SpringApplication.run LumenSocialApplication, args
    }

    @Override
    void run(String... args) throws Exception {
        log.info('Joining thread, you can press Ctrl+C to shutdown application')
        Thread.currentThread().join()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这将破坏使用SpringBootTest注解的集成测试。 (2认同)

jmk*_*een 17

从Apache Camel 2.17开始,有一个更清晰的答案.引用http://camel.apache.org/spring-boot.html:

要阻止主线程以便Camel保持运行,请包含spring-boot-starter-web依赖项,或者将camel.springboot.main-run-controller = true添加到application.properties或application.yml文件中.

您还需要以下依赖项:

<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-boot-starter</artifactId> <version>2.17.0</version> </dependency>

明确替换<version>2.17.0</version>或使用驼峰BOM导入依赖管理信息以保持一致性.


Wil*_*eez 7

使用CountDownLatch的示例实现:

@Bean
public CountDownLatch closeLatch() {
    return new CountDownLatch(1);
}

public static void main(String... args) throws InterruptedException {
    ApplicationContext ctx = SpringApplication.run(MyApp.class, args);  

    final CountDownLatch closeLatch = ctx.getBean(CountDownLatch.class);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            closeLatch.countDown();
        }
    });
    closeLatch.await();
}
Run Code Online (Sandbox Code Playgroud)

现在要停止应用程序,您可以从控制台查找进程ID并发出kill命令:

kill <PID>
Run Code Online (Sandbox Code Playgroud)


Ana*_*oly 5

Spring Boot 将运行应用程序的任务留给了实现应用程序所围绕的协议。例如,请参阅本指南

还需要一些内务对象,例如CountDownLatch保持主线程处于活动状态的...

例如,运行 Camel 服务的方式是从主 Spring Boot 应用程序类将 Camel 作为独立应用程序运行。

  • “本指南”链接已损坏。 (2认同)