Apache Camel:带调度程序的FTP文件(目录为空时关闭连接)

时间:2016-03-08 11:08:33

标签: java ftp apache-camel

我想使用Apache Camel将文件从本地目录发送到FTP位置。我们每天只在该本地目录中获得1或2次文件。所以没有必要让这个连接全天开放。我想要实现的是,当目录中有文件时我们将打开连接(这是我们可以通过检查目录来完成的),但我们如何检查是否已完成使用Apache Camel发送文件并关闭连接?

是否有一些来自RouteBuilder的反馈或者实现这一目标的最佳方法是什么?

由于

2 个答案:

答案 0 :(得分:2)

发送完成后,您可以使用disconnect=true选项关闭连接。

请参阅以下文档:http://camel.apache.org/ftp2

答案 1 :(得分:-1)

我使用FTPToClientRouteBuilder解决了这个问题,该方法在以下方法中调用:

@Override
public void sentFilesViaFTPToClient() {

    CamelContext context = new DefaultCamelContext();

    try {
        context.addRoutes(new FTPToClientRouteBuilder());
        context.start();

        while (true) {
            if (CollectionUtils.isEmpty(context.getRoutes())) {
                LOG.info("Finished sending files via FTP.");
                context.stop();
                break;
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Couldn't FTP files", e);
    } finally {
        try {
            context.stop();
        } catch (Exception e) {
            //ignore exception
        }
    }
}

FTPToClientRouteBuilder

public class FTPToClientRouteBuilder extends RouteBuilder {

private static final Logger LOG = LoggerFactory.getLogger(FTPToClientRouteBuilder.class);

private String ftpLocation;
private String uploadLocation = "file:" + location + "?delete=true&moveFailed=../error&sendEmptyMessageWhenIdle=true";

@Override
public void configure() throws Exception {

    // set graceful shutdown timeout
    getContext().getShutdownStrategy().setTimeout(10);

    from(uploadLocation)
        .choice()
            .when(body().isNotNull())
            .log("Uploading file ${file:name}")
            .to(ftpLocation)
            .log("Uploaded file ${file:name} complete.")
        .otherwise()
        .process(new ShutdownProcessor());
}

private class ShutdownProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {
        new Thread() {
            @Override
            public void run() {
                try {
                    exchange.getContext().stop();
                } catch (Exception e) {
                    LOG.error("Couldn't stop the route", e);
                }
            }
        }.start();
    }
}
}