简体   繁体   English

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

[英]How do I make a standalone Camel application that can automatically shutdown?

I have a simple file transfer application that is run as a standalone Java application. 我有一个简单的文件传输应用程序,作为独立的Java应用程序运行。 It takes files from an SFTP endpoint and moves them to another endpoint. 它从SFTP端点获取文件并将它们移动到另一个端点。

Files are deleted from the SFTP endpoint after they are transferred. 传输后,文件将从SFTP端点中删除。 When there are no more files left, it would be ideal to have the program end . 当没有剩余文件时,最好让程序结束 However, I haven't been able to find a solution where I can start Camel and get it to end conditionally (like when there are no more files in the SFTP endpoint) . 但是,我无法找到一个解决方案,我可以启动Camel并使其有条件结束(例如,当SFTP端点中没有更多文件时) My workaround is currently to start Camel and then have the main thread sleep for a very long time. 我的解决方法是启动Camel,然后让主线程休眠很长一段时间。 The user then has to kill the application manually (via CTRL+C or otherwise). 然后,用户必须手动终止应用程序(通过CTRL + C或其他方式)。

Is there a better way to have the application terminate such that it does so automatically? 是否有更好的方法让应用程序终止,以便它自动完成?

Below is my current code: 以下是我目前的代码:

In CamelContext (Spring App Context): 在CamelContext(Spring App Context)中:

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

main() method: 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");
}

You could change you route something like this: 你可以改变你这样的路线:

<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>

Notice using sendEmptyMessageWhenIdle=true 请注意使用sendEmptyMessageWhenIdle=true

And here is shutdownProcessor 这是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();
    }
}

Actually I didn't run this code, but it should work as desired. 实际上我没有运行此代码,但它应该按照需要工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM