6

I'm trying to use Apache Camel to download and route files from an FTP server. However, files are only added to the FTP server once in a long while so having the program running continuously seems a bit overzealous. Instead, I would rather have a cronjob that runs weekly and processes any new files that have been added to the server.

Is there any way to get Camel to automatically shutdown once it no longer has any new files to process?

My current main function looks like this:

public static void main (String[] args) throws Exception {
    org.apache.camel.spring.Main main = new org.apache.camel.spring.Main ();
    main.setApplicationContextUri ("applicationContext.xml");
    main.enableHangupSupport ();
    main.run (args);
}

And the interesting part of the applicationContext.xml is:

<camelContext>
    <route>
        <from uri="ftp://ftp.example.com/remoteDir?username=user&amp;password=pass"/>
        <to uri="file:../ftp_data?tempPrefix=."/>
    </route>
</camelContext>
4

3 回答 3

5

添加此示例可能对其他人有用,而无需挖掘链接中的所有示例。

定义一个将启动单独线程的 bean/处理器。这个新线程将调用stop()active CamelContext

public class ShutdownBean {

    private final static Logger log = LoggerFactory.getLogger(ShutdownBean.class);

    public void process(Exchange exchange) throws Exception {
        final CamelContext camelContext = exchange.getContext();

        Thread shutdownThread = new Thread(() -> {
            Thread.currentThread().setName("ShutdownThread");
            try {
                camelContext.stop();
            } catch (Exception e) {
                log.error("Errore during shutdown", e);
            }
        });

        shutdownThread.start();
    }
}

在您的应用程序上下文中定义此路由并在需要关闭 Camel 时调用它。

<bean id="shutdownBean"
      class="your.package.ShutdownBean" />

<camelContext>

    <route id="ShutdownRoute">
        <from uri="direct:shutdown" />
        <log message="Shutdown..." />
        <to uri="bean:shutdownBean" />
    </route>

</camelContext>

注意enableHangupSupport()在较新的 Camel 版本上已弃用:现在默认启用,因此不再需要调用此方法。

于 2016-09-01T15:12:57.603 回答
4

请参阅此常见问题解答如何从路线停止路线:http ://camel.apache.org/how-can-i-stop-a-route-from-a-route.html 。

然后你可以启用选项:sendEmptyMessageWhenIdle=true,然后在路由中做一个消息过滤,或者基于内容的路由,并检测空消息,然后停止路由,然后在那个 CamelContext 之后。

虽然我也认为这个问题之前已经讨论过,所以你也许可以找到其他 SO 问题或谷歌等。因为还有其他方法可以做到这一点。

于 2013-06-29T06:52:27.753 回答
2

完成克劳斯的回答后,这段代码以一种只有一次的方式运行主要:

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class MyMainRouter extends RouteBuilder {

  static Main main;

  @Override
  public void configure() throws Exception {
    from("timer:foo?delay=5s")
        .log("Hello camel, main world after 5 seconds!")
        .process(processor -> main.completed());
  }

  public static void main(String[] args) throws Exception {
    main = new Main();
    main.addRouteBuilder(new MyMainRouter());
    main.run();
  }

}

5 秒后,代码将只运行一次,因为我们将调用一个处理器,该处理器将调用 completed() 方法,内部有 CountDownLatch 停止来自另一个线程的路由模式。

于 2018-07-16T13:09:25.357 回答