Spring Boot-在部署时启动后台线程的最佳方法 [英] Spring Boot - Best way to start a background thread on deployment

查看:1842
本文介绍了Spring Boot-在部署时启动后台线程的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Tomcat 8中部署了一个Spring Boot应用程序.当该应用程序启动时,我想在Spring Autowires具有某些依赖项的后台启动一个工作线程.目前我有这个:

I have a Spring Boot application deployed in Tomcat 8. When the application starts I want to start a worker Thread in the background that Spring Autowires with some dependencies. Currently I have this :

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
public class MyServer extends SpringBootServletInitializer {   

    public static void main(String[] args) {
        log.info("Starting application");
        ApplicationContext ctx = SpringApplication.run(MyServer.class, args);
        Thread subscriber = new Thread(ctx.getBean(EventSubscriber.class));
        log.info("Starting Subscriber Thread");
        subscriber.start();
    }

在我的Docker测试环境中,它工作得很好-但是当我将它部署到Tomcat 8中的Linux(Debian Jessie,Java 8)主机时,我再也看不到正在启动订户线程"消息(并且该线程未启动)

In my Docker test environment this works just fine - but when I deploy this to my Linux (Debian Jessie, Java 8) host in Tomcat 8 I never see the "Starting Subscriber Thread" message (and the thread is not started).

推荐答案

将应用程序部署到非嵌入式应用程序服务器时,不会调用main方法. 启动线程的最简单方法是从bean构造函数执行该操作. 关闭上下文时清理线程也是一个好主意,例如:

The main method is not called when deploying the application to a non-embedded application server. The simplest way to start a thread is to do it from the beans constructor. Also a good idea to clean up the thread when the context is closed, for example:

@Component
class EventSubscriber implements DisposableBean, Runnable {

    private Thread thread;
    private volatile boolean someCondition;

    EventSubscriber(){
        this.thread = new Thread(this);
        this.thread.start();
    }

    @Override
    public void run(){
        while(someCondition){
            doStuff();
        }
    }

    @Override
    public void destroy(){
        someCondition = false;
    }

}

这篇关于Spring Boot-在部署时启动后台线程的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆