2012-10-16 16 views
5

我有一個簡單的文件傳輸應用程序作爲獨立的Java應用程序運行。它從SFTP端點獲取文件並將它們移動到另一個端點。如何製作可以自動關機的獨立Camel應用程序?

文件在傳輸後從SFTP端點中刪除。 當沒有更多文件時,最好讓程序結束。然而,我一直沒能找到一個解決方案,我可以啓動Camel,並有條件地結束到的末端(如SFTP端點中沒有更多文件)。我的解決方法是當前啓動駱駝,然後讓主線程睡很長時間。用戶然後必須手動殺死該應用程序(通過CTRL + C或其他方式)。

有沒有更好的方法讓應用程序終止,以便它自動執行?

下面是我當前的代碼:

在CamelContext(春季應用程序上下文):

<route> 
    <from uri="sftp:(url)" /> 
    <process ref="(processor)" /> 
    <to uri="(endpoint)" /> 
</route> 

main()方法:

public static void main(String[] args) 
{ 
    ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 
    CamelContext camelContext = appContext.getBean(CamelContext.class); 

    try 
    { 
    camelContext.start(); 
    Thread.sleep(1000000000); // Runs the program for a long time -- is there a better way? 
    } 
    catch (Exception e) 
    { 
    e.printStackTrace(); 
    } 

    UploadContentLogger.info("Exiting"); 
} 

回答

5

你可以改變你的路線是這樣的:

<route> 
    <from uri="sftp:(url)?sendEmptyMessageWhenIdle=true" /> 
    <choose> 
     <when> 
      <simple>${body} != null</simple> 
      <process ref="(processor)" /> 
      <to uri="(endpoint)" /> 
     </when> 
     <otherwise> 
      <process ref="(shutdownProcessor)" /> 
     </otherwise> 
    </choose> 
</route> 

注意使用sendEmptyMessageWhenIdle=true

這裏是shutdownProcessor

public class ShutdownProcessor { 
    public void stop(final Exchange exchange) { 
     new Thread() { 
      @Override 
      public void run() { 
       try { 
        exchange.getContext().stop(); 
       } catch (Exception e) { 
        // log error 
       } 
      } 
     }.start(); 
    } 
} 

其實我沒有運行此代碼,但期望它應該工作。

相關問題