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)
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导入依赖管理信息以保持一致性.
使用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)
| 归档时间: |
|
| 查看次数: |
25029 次 |
| 最近记录: |