如何以自动方式关闭独立的 Apache Camel 应用程序?

Kei*_*ith 6 java apache-camel

我正在尝试使用 Apache Camel 从 FTP 服务器下载和路由文件。然而,文件只是偶尔添加到 FTP 服务器,所以让程序连续运行似乎有点过分热情。相反,我宁愿有一个每周运行的 cronjob 并处理已添加到服务器的任何新文件。

一旦不再有任何新文件要处理,有没有办法让 Camel 自动关闭?

我当前的main功能如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

有趣的部分applicationContext.xml是:

<camelContext>
    <route>
        <from uri="ftp://ftp.example.com/remoteDir?username=user&amp;password=pass"/>
        <to uri="file:../ftp_data?tempPrefix=."/>
    </route>
</camelContext>
Run Code Online (Sandbox Code Playgroud)

Ale*_*gna 5

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

定义将启动单独线程的 bean/处理器。这个新线程将调用stop()活动的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的应用程序上下文中定义此路由并在您需要关闭 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>
Run Code Online (Sandbox Code Playgroud)

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

  • 更新:所以问题最终与没有正确附加到文件组件的选项有关。我有 uri="file://path/to/dir?option1=val1?option2=val2 而应该是 uri="file://path/to/dir?option1=val1&amp;option2=val2。没有令人沮丧地抛出错误;该任务将在camelContext 关闭后挂起。事实证明,通过 &amp; 转义“&amp;”符号 非常重要。 (2认同)

Cla*_*sen 4

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

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

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