如何创建可以自动关闭的独立Camel应用程序?

时间:2012-10-16 16:01:12

标签: java apache-camel

我有一个简单的文件传输应用程序,它作为独立的Java应用程序运行。它从SFTP端点获取文件并将它们移动到另一个端点。

文件在传输后从SFTP端点删除。 当没有剩余文件时,最好让程序结束。但是,我无法找到一个解决方案,我可以启动Camel并将其设置为有条件地结束(例如,当SFTP端点中没有更多文件时)。我的解决方法是启动Camel,然后让主线程休眠很长一段时间。然后,用户必须手动终止应用程序(通过CTRL + C或其他方式)。

是否有更好的方法让应用程序终止,以便自动执行此操作?

以下是我目前的代码:

在CamelContext(Spring App Context)中:

<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");
}

2 个答案:

答案 0 :(得分: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();
    }
}

实际上我没有运行此代码,但它应该可以正常工作。

答案 1 :(得分:1)

我还想向您指出此常见问题解答 http://camel.apache.org/how-can-i-stop-a-route-from-a-route.html