2016-08-02 40 views
1

我有一個過程,是一個無限循環:如何在Spring Boot中管理無限過程?

public class MyProcess { 

    public void start() { 
     while (true) { 
      //process 
     } 
    } 
} 

當我開始使用Spring的引導,我的第一個方法是讓從上下文的bean的應用程序已經開始後,手動啓動過程:

@SpringBootApplication 
public class MyApplication { 

    public static void main(String[] args) { 
     ApplicationContext applicationContext = SpringApplication.run(MyApplication.class, args); 

     MyProcess myProcess = applicationContext.getBean(MyProcess.class); 
     myProcess.start(); 
    } 
} 

這工作,但似乎並不喜歡做的正確的方式,讓我實現了一個CommandLineRunner

@Component 
public class MyRunner implements CommandLineRunner { 

    @Autowired 
    private MyProcess myProcess; 

    @Override 
    public void run(String... args) { 
     this.myProcess.start(); 
    } 
} 

這跟以前幾乎一樣,但這裏的SpringApplication#run調用從未實際完成,這似乎也是錯誤的。 我想對不對?

然後我試着用Executor我自己管理這個,但爲了捕捉任何Exception我不得不打電話Future#get導致在相同的阻斷狀態。

取而代之,我現在在CommandLineRunner#run方法上使用@Async註釋。

這似乎是最好的解決方案,因爲應用程序在任務啓動後完成啓動。任何Exception將被選中並記錄下來,但由Sprint創建的支持Executor會阻止應用程序關閉。

我假設有一種方法要求Spring終止Executor,這樣整個應用程序就可以退出了,因爲我使用Supervisor在外部管理它。

這是正確的方法還是我錯過了一個步驟?應用程序是否應該獨立並在發生故障後重新啓動進程?

回答

0

在主線程中做一些工作。從main()撥打myProcess.start()而沒有@Async有什麼問題?當你完成你的工作只是離開循環MyProcess#start

+0

這是我做的第一,但我從來沒有見過,在任何例子,所以我不知道。那麼CommandLineRunner的目的是什麼? – Djon

+0

@Djon我有同樣的問題。看起來這是一種在運行環境中使用注入bean訪問命令行參數的方式(在應用程序啓動後)。我使用命令行應用程序的CommandLineRunner接口 – ruX

相關問題