FTP/FTPS适配器

FTP/FTPS 适配器

Spring Integration 支持使用 FTP 和 FTPS 进行文件传输作。spring-doc.cadn.net.cn

文件传输协议 (FTP) 是一种简单的网络协议,可让您在 Internet 上的两台计算机之间传输文件。 FTPS 代表“FTP over SSL”。spring-doc.cadn.net.cn

您需要将此依赖项包含在您的项目中:spring-doc.cadn.net.cn

专家
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-ftp</artifactId>
    <version>6.0.9</version>
</dependency>
Gradle
compile "org.springframework.integration:spring-integration-ftp:6.0.9"

在 FTP 通信方面,有两个参与者:客户端和服务器。 若要使用 FTP 或 FTPS 传输文件,请使用启动与运行 FTP 服务器的远程计算机的连接的客户端。 建立连接后,客户端可以选择发送或接收文件副本。spring-doc.cadn.net.cn

Spring Integration 通过提供三个客户端端点来支持通过 FTP 或 FTPS 发送和接收文件:入站通道适配器、出站通道适配器和出站网关。 它还提供了方便的基于命名空间的配置选项来定义这些客户端组件。spring-doc.cadn.net.cn

要使用 FTP 命名空间,请将以下内容添加到 XML 文件的标头中:spring-doc.cadn.net.cn

xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp"
xsi:schemaLocation="http://www.springframework.org/schema/integration/ftp
    https://www.springframework.org/schema/integration/ftp/spring-integration-ftp.xsd"

FTP 会话工厂

Spring Integration提供了可用于创建FTP(或FTPS)会话的工厂。spring-doc.cadn.net.cn

默认工厂

从 3.0 版开始,默认情况下不再缓存会话。 请参阅 FTP 会话缓存

在配置 FTP 适配器之前,必须配置 FTP 会话工厂。 您可以使用常规 bean 定义配置 FTP 会话工厂,其中实现类为o.s.i.ftp.session.DefaultFtpSessionFactory. 以下示例显示了基本配置:spring-doc.cadn.net.cn

<bean id="ftpClientFactory"
    class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
    <property name="host" value="localhost"/>
    <property name="port" value="22"/>
    <property name="username" value="kermit"/>
    <property name="password" value="frog"/>
    <property name="clientMode" value="0"/>
    <property name="fileType" value="2"/>
    <property name="bufferSize" value="100000"/>
</bean>

对于 FTPS 连接,您可以使用o.s.i.ftp.session.DefaultFtpsSessionFactory相反。spring-doc.cadn.net.cn

以下示例显示了完整的配置:spring-doc.cadn.net.cn

<bean id="ftpClientFactory"
    class="org.springframework.integration.ftp.session.DefaultFtpsSessionFactory">
    <property name="host" value="localhost"/>
    <property name="port" value="22"/>
    <property name="username" value="oleg"/>
    <property name="password" value="password"/>
    <property name="clientMode" value="1"/>
    <property name="fileType" value="2"/>
    <property name="useClientMode" value="true"/>
    <property name="cipherSuites" value="a,b.c"/>
    <property name="keyManager" ref="keyManager"/>
    <property name="protocol" value="SSL"/>
    <property name="trustManager" ref="trustManager"/>
    <property name="prot" value="P"/>
    <property name="needClientAuth" value="true"/>
    <property name="authValue" value="oleg"/>
    <property name="sessionCreation" value="true"/>
    <property name="protocols" value="SSL, TLS"/>
    <property name="implicit" value="true"/>
</bean>
如果您遇到连接问题,并且想要跟踪会话创建并查看轮询了哪些会话,您可以通过将记录器设置为TRACE级别(例如,log4j.category.org.springframework.integration.file=TRACE).

现在,您只需将这些会话工厂注入适配器中。 适配器使用的协议(FTP 或 FTPS)取决于已注入适配器的会话工厂类型。spring-doc.cadn.net.cn

为 FTP 或 FTPS 会话工厂提供值的更实用的方法是使用 Spring 的属性占位符支持(参见 https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-placeholderconfigurer)。

高级配置

DefaultFtpSessionFactory提供了对底层客户端 API 的抽象,该 API(自 Spring Integration 2.0 以来)是 Apache Commons Net。 这样,您就可以免于使用org.apache.commons.net.ftp.FTPClient. 会话工厂上公开了几个常见属性(从 4.0 版开始,现在包括connectTimeout,defaultTimeoutdataTimeout). 但是,有时您需要访问较低级别FTPClient配置以实现更高级的配置(例如设置活动模式的端口范围)。 为此,AbstractFtpSessionFactory(所有 FTP 会话工厂的基类)以以下列表中所示的两种后处理方法的形式公开钩子:spring-doc.cadn.net.cn

/**
 * Will handle additional initialization after client.connect() method was invoked,
 * but before any action on the client has been taken
 */
protected void postProcessClientAfterConnect(T t) throws IOException {
    // NOOP
}
/**
 * Will handle additional initialization before client.connect() method was invoked.
 */
protected void postProcessClientBeforeConnect(T client) throws IOException {
    // NOOP
}

如您所见,这两种方法没有默认实现。 但是,通过扩展DefaultFtpSessionFactory,您可以覆盖这些方法以提供更高级的FTPClient,如以下示例所示:spring-doc.cadn.net.cn

public class AdvancedFtpSessionFactory extends DefaultFtpSessionFactory {

    protected void postProcessClientBeforeConnect(FTPClient ftpClient) throws IOException {
       ftpClient.setActivePortRange(4000, 5000);
    }
}

FTPS 和共享 SSLSession

使用 FTP over SSL 或 TLS 时,某些服务器需要相同的SSLSession用于控制和数据连接。 这是为了防止“窃取”数据连接。 有关详细信息,请参阅 https://scarybeastsecurity.blogspot.cz/2009/02/vsftpd-210-released.htmlspring-doc.cadn.net.cn

目前,Apache FTPSClient 不支持此功能。 参见 NET-408spring-doc.cadn.net.cn

以下解决方案由 Stack Overflow 提供,使用对sun.security.ssl.SSLSessionContextImpl,因此它可能不适用于其他 JVM。 堆栈溢出答案于 2015 年提交,该解决方案已由 Spring Integration 团队在 JDK 1.8.0_112 上进行了测试。spring-doc.cadn.net.cn

以下示例演示如何创建 FTPS 会话:spring-doc.cadn.net.cn

@Bean
public DefaultFtpsSessionFactory sf() {
    DefaultFtpsSessionFactory sf = new DefaultFtpsSessionFactory() {

        @Override
        protected FTPSClient createClientInstance() {
            return new SharedSSLFTPSClient();
        }

    };
    sf.setHost("...");
    sf.setPort(21);
    sf.setUsername("...");
    sf.setPassword("...");
    sf.setNeedClientAuth(true);
    return sf;
}

private static final class SharedSSLFTPSClient extends FTPSClient {

    @Override
    protected void _prepareDataSocket_(final Socket socket) throws IOException {
        if (socket instanceof SSLSocket) {
            // Control socket is SSL
            final SSLSession session = ((SSLSocket) _socket_).getSession();
            final SSLSessionContext context = session.getSessionContext();
            context.setSessionCacheSize(0); // you might want to limit the cache
            try {
                final Field sessionHostPortCache = context.getClass()
                        .getDeclaredField("sessionHostPortCache");
                sessionHostPortCache.setAccessible(true);
                final Object cache = sessionHostPortCache.get(context);
                final Method method = cache.getClass().getDeclaredMethod("put", Object.class,
                        Object.class);
                method.setAccessible(true);
                String key = String.format("%s:%s", socket.getInetAddress().getHostName(),
                        String.valueOf(socket.getPort())).toLowerCase(Locale.ROOT);
                method.invoke(cache, key, session);
                key = String.format("%s:%s", socket.getInetAddress().getHostAddress(),
                        String.valueOf(socket.getPort())).toLowerCase(Locale.ROOT);
                method.invoke(cache, key, session);
            }
            catch (NoSuchFieldException e) {
                // Not running in expected JRE
                logger.warn("No field sessionHostPortCache in SSLSessionContext", e);
            }
            catch (Exception e) {
                // Not running in expected JRE
                logger.warn(e.getMessage());
            }
        }

    }

}

委托会话工厂

4.2 版引入了DelegatingSessionFactory,这允许在运行时选择实际的会话工厂。 在调用 FTP 终结点之前,调用setThreadKey()在工厂上将键与当前线程相关联。 然后,该键用于查找要使用的实际会话工厂。 您可以通过调用clearThreadKey()使用后。spring-doc.cadn.net.cn

我们添加了方便的方法,以便您可以轻松地从消息流中使用委托会话工厂。spring-doc.cadn.net.cn

以下示例演示如何声明委托会话工厂:spring-doc.cadn.net.cn

<bean id="dsf" class="org.springframework.integration.file.remote.session.DelegatingSessionFactory">
    <constructor-arg>
        <bean class="o.s.i.file.remote.session.DefaultSessionFactoryLocator">
            <!-- delegate factories here -->
        </bean>
    </constructor-arg>
</bean>

<int:service-activator input-channel="in" output-channel="c1"
        expression="@dsf.setThreadKey(#root, headers['factoryToUse'])" />

<int-ftp:outbound-gateway request-channel="c1" reply-channel="c2" ... />

<int:service-activator input-channel="c2" output-channel="out"
        expression="@dsf.clearThreadKey(#root)" />
使用会话缓存时(请参阅 FTP 会话缓存),应缓存每个委托。您无法缓存DelegatingSessionFactory本身。

从 5.0.7 版本开始,DelegatingSessionFactory可以与RotatingServerAdvice轮询多个服务器;请参阅入站通道适配器:轮询多个服务器和目录spring-doc.cadn.net.cn

FTP 入站通道适配器

FTP 入站通道适配器是一个特殊的侦听器,它连接到 FTP 服务器并侦听远程目录事件(例如,创建的新文件),此时它启动文件传输。 以下示例演示如何配置inbound-channel-adapter:spring-doc.cadn.net.cn

<int-ftp:inbound-channel-adapter id="ftpInbound"
    channel="ftpChannel"
    session-factory="ftpSessionFactory"
    auto-create-local-directory="true"
    delete-remote-files="true"
    filename-pattern="*.txt"
    remote-directory="some/remote/path"
    remote-file-separator="/"
    preserve-timestamp="true"
    local-filename-generator-expression="#this.toUpperCase() + '.a'"
    scanner="myDirScanner"
    local-filter="myFilter"
    temporary-file-suffix=".writing"
    max-fetch-size="-1"
    local-directory=".">
    <int:poller fixed-rate="1000"/>
</int-ftp:inbound-channel-adapter>

如上述配置所示,您可以使用inbound-channel-adapter元素,同时还为各种属性提供值,例如local-directory,filename-pattern(基于简单的模式匹配,而不是正则表达式),以及对session-factory.spring-doc.cadn.net.cn

默认情况下,传输的文件与原始文件具有相同的名称。 如果要覆盖此行为,可以将local-filename-generator-expression属性,它允许您提供 SpEL 表达式来生成本地文件的名称。 与出站网关和适配器不同,其中 SpEL 评估上下文的根对象是Message,则此入站适配器在评估时尚未收到该消息,因为这是它最终生成的将传输的文件作为其有效负载的内容。 因此,SpEL 求值上下文的根对象是远程文件的原始名称 (String).spring-doc.cadn.net.cn

入站通道适配器首先检索File对象,然后根据轮询器配置发出每个文件。 从 5.0 版开始,现在可以限制在需要检索新文件时从 FTP 服务器获取的文件数量。 当目标文件非常大时,或者当您在具有持久性文件列表过滤器的群集系统中运行时,这可能会很有用,稍后将讨论。 用max-fetch-size为此目的。 负值(默认值)表示没有限制,并且会检索所有匹配的文件。 有关更多信息,请参阅入站通道适配器:控制远程文件获取。 从 5.0 版本开始,您还可以提供自定义DirectoryScanner实现到inbound-channel-adapter通过将scanner属性。spring-doc.cadn.net.cn

从 Spring Integration 3.0 开始,您可以指定preserve-timestamp属性(其默认值为false). 什么时候true,则本地文件的修改时间戳设置为从服务器检索的值。 否则,它设置为当前时间。spring-doc.cadn.net.cn

从 4.2 版开始,您可以指定remote-directory-expression而不是remote-directory,让您动态确定每次轮询的目录 — 例如remote-directory-expression="@myBean.determineRemoteDir()".spring-doc.cadn.net.cn

从 4.3 版开始,您可以省略remote-directoryremote-directory-expression属性。 它们默认为null. 在这种情况下,根据FTP协议,客户端工作目录被用作默认的远程目录。spring-doc.cadn.net.cn

有时,基于filename-pattern属性可能不够。 如果是这种情况,您可以使用filename-regex属性来指定正则表达式(例如filename-regex=".*\.test$"). 此外,如果您需要完全控制,您可以使用filter属性,并提供对o.s.i.file.filters.FileListFilter,用于过滤文件列表的策略接口。 此过滤器确定要检索哪些远程文件。 您还可以将基于模式的过滤器与其他过滤器(例如AcceptOnceFileListFilter以避免同步以前获取的文件),使用CompositeFileListFilter.spring-doc.cadn.net.cn

AcceptOnceFileListFilter将其状态存储在内存中。 如果您希望状态在系统重新启动后继续存在,请考虑使用FtpPersistentAcceptOnceFileListFilter相反。 此过滤器将接受的文件名存储在MetadataStore策略(请参阅元数据存储)。 此过滤器与文件名和远程修改时间相匹配。spring-doc.cadn.net.cn

从 4.0 版开始,此过滤器需要ConcurrentMetadataStore. 与共享数据存储(例如Redis使用RedisMetadataStore),它允许在多个应用程序或服务器实例之间共享过滤器键。spring-doc.cadn.net.cn

从 5.0 版开始,FtpPersistentAcceptOnceFileListFilter带内存SimpleMetadataStore默认情况下应用于FtpInboundFileSynchronizer. 此过滤器还与regexpattern选项以及FtpInboundChannelAdapterSpec在 Java DSL 中。 任何其他用例都可以通过CompositeFileListFilter(或ChainFileListFilter).spring-doc.cadn.net.cn

前面的讨论是指在检索文件之前对其进行过滤。 检索文件后,将对文件系统上的文件应用额外的过滤器。 默认情况下,这是一个AcceptOnceFileListFilter如前所述,它将状态保留在内存中,并且不考虑文件的修改时间。 除非应用程序在处理后删除文件,否则适配器将在应用程序重新启动后默认重新处理磁盘上的文件。spring-doc.cadn.net.cn

此外,如果您配置filter使用FtpPersistentAcceptOnceFileListFilter并且远程文件时间戳更改(导致它被重新获取),默认的本地过滤器不允许处理这个新文件。spring-doc.cadn.net.cn

有关此筛选器及其使用方式的详细信息,请参阅远程持久文件列表筛选器spring-doc.cadn.net.cn

您可以使用local-filter属性来配置本地文件系统过滤器的行为。 从 4.3.8 版本开始,FileSystemPersistentAcceptOnceFileListFilter默认配置。 此过滤器将接受的文件名和修改的时间戳存储在MetadataStore策略(请参阅元数据存储)并检测对本地文件修改时间的更改。 默认值MetadataStore是一个SimpleMetadataStore,将状态存储在内存中。spring-doc.cadn.net.cn

从版本 4.1.5 开始,这些过滤器有一个新属性 (flushOnUpdate),导致它们冲洗 元数据存储(如果存储实现Flushable).spring-doc.cadn.net.cn

此外,如果您使用分布式MetadataStore(例如 Redis),您可以拥有同一适配器或应用程序的多个实例,并确保每个文件仅处理一次。

实际的本地过滤器是CompositeFileListFilter包含提供的过滤器和模式过滤器,该过滤器可防止处理正在下载的文件(基于temporary-file-suffix). 下载带有此后缀的文件(默认值为.writing),并且传输完成后文件将重命名为其最终名称,使其对过滤器“可见”。spring-doc.cadn.net.cn

remote-file-separator属性允许您配置文件分隔符,以便在默认“/”不适用于您的特定环境时使用。spring-doc.cadn.net.cn

有关这些属性的更多详细信息,请参阅架构spring-doc.cadn.net.cn

您还应该了解 FTP 入站通道适配器是轮询使用者。 因此,您必须配置轮询器(通过使用全局默认值或本地子元素)。 传输文件后,将收到一条带有java.io.File当其有效负载被生成并发送到由channel属性。spring-doc.cadn.net.cn

有关文件过滤和不完整文件的更多信息

有时,刚刚出现在受监控(远程)目录中的文件不完整。 通常,此类文件是使用临时扩展名(例如somefile.txt.writing),然后在写入过程完成后重命名。 在大多数情况下,您只对完整的文件感兴趣,并且只想筛选完整的文件。 若要处理这些方案,可以使用filename-pattern,filename-regexfilter属性。 以下示例使用自定义筛选器实现:spring-doc.cadn.net.cn

<int-ftp:inbound-channel-adapter
    channel="ftpChannel"
    session-factory="ftpSessionFactory"
    filter="customFilter"
    local-directory="file:/my_transfers">
    remote-directory="some/remote/path"
    <int:poller fixed-rate="1000"/>
</int-ftp:inbound-channel-adapter>

<bean id="customFilter" class="org.example.CustomFilter"/>

入站 FTP 适配器的轮询器配置说明

入站 FTP 适配器的作业包括两个任务:spring-doc.cadn.net.cn

  1. 与远程服务器通信,以便将文件从远程目录传输到本地目录。spring-doc.cadn.net.cn

  2. 对于每个传输的文件,生成一条消息,其中包含该文件作为有效负载,并将其发送到由“channel”属性标识的通道。 这就是为什么它们被称为“'通道适配器'”而不仅仅是“'适配器'”。 此类适配器的主要工作是生成要发送到消息通道的消息。 从本质上讲,第二个任务优先于此,如果您的本地目录已经有一个或多个文件,它首先从这些文件生成消息。 只有当所有本地文件都处理完毕后,它才会启动远程通信以检索更多文件。spring-doc.cadn.net.cn

此外,在轮询器上配置触发器时,应密切注意max-messages-per-poll属性。 其默认值为1对于所有人SourcePollingChannelAdapter实例(包括 FTP)。 这意味着,一旦处理了一个文件,它就会等待由触发器配置确定的下一个执行时间。 如果您碰巧有一个或多个文件位于local-directory,它将在启动与远程 FTP 服务器的通信之前处理这些文件。 此外,如果max-messages-per-poll设置为1(默认值),它一次只处理一个文件,间隔由触发器定义,本质上是“one-poll === one-file”。spring-doc.cadn.net.cn

对于典型的文件传输用例,您很可能希望采取相反的行为:为每次轮询处理所有文件,然后才等待下一次轮询。 如果是这种情况,请将max-messages-per-poll设置为 -1。 然后,在每次轮询时,适配器都会尝试生成尽可能多的消息。 换句话说,它处理本地目录中的所有内容,然后连接到远程目录以传输那里可用的所有内容以在本地处理。 只有这样,轮询作才被视为完成,轮询器等待下一个执行时间。spring-doc.cadn.net.cn

或者,您可以将“每次轮询的 max-messages”值设置为正值,该值指示每次轮询时要从文件创建的消息的上限。 例如,值10表示在每次轮询时,它尝试处理不超过十个文件。spring-doc.cadn.net.cn

从故障中恢复

了解适配器的架构非常重要。 有一个文件同步器可以获取文件,并且有一个FileReadingMessageSource为每个 synchronized 文件。 如前所述,涉及两个过滤器。 这filter属性(和模式)引用远程 (FTP) 文件列表,以避免获取已经 被取来。 这local-filterFileReadingMessageSource以确定哪些文件将作为消息发送。spring-doc.cadn.net.cn

同步器列出远程文件并查阅其过滤器。 然后传输文件。 如果在文件传输过程中发生 IO 错误,则会删除已添加到过滤器中的所有文件,以便它们 有资格在下一次轮询中重新获取。 这仅适用于过滤器实现ReversibleFileListFilter(例如AcceptOnceFileListFilter).spring-doc.cadn.net.cn

如果在同步文件后,处理文件的下游流发生错误,则不会发生过滤器的自动回滚,因此默认情况下不会重新处理失败的文件。spring-doc.cadn.net.cn

如果希望在失败后重新处理此类文件,可以使用类似于以下的配置来方便 从过滤器中删除失败的文件:spring-doc.cadn.net.cn

<int-ftp:inbound-channel-adapter id="ftpAdapter"
        session-factory="ftpSessionFactory"
        channel="requestChannel"
        remote-directory-expression="'/ftpSource'"
        local-directory="file:myLocalDir"
        auto-create-local-directory="true"
        filename-pattern="*.txt">
    <int:poller fixed-rate="1000">
        <int:transactional synchronization-factory="syncFactory" />
    </int:poller>
</int-ftp:inbound-channel-adapter>

<bean id="acceptOnceFilter"
    class="org.springframework.integration.file.filters.AcceptOnceFileListFilter" />

<int:transaction-synchronization-factory id="syncFactory">
    <int:after-rollback expression="payload.delete()" />
</int:transaction-synchronization-factory>

<bean id="transactionManager"
    class="org.springframework.integration.transaction.PseudoTransactionManager" />

上述配置适用于任何ResettableFileListFilter.spring-doc.cadn.net.cn

从 V5.0 开始,入站通道适配器可以在本地构建与生成的本地文件名相对应的子目录。 这也可以是一个远程子路径。 为了能够递归地读取本地目录以根据层次结构支持进行修改,您现在可以提供一个内部FileReadingMessageSource使用新的RecursiveDirectoryScanner基于Files.walk()算法。 看AbstractInboundFileSynchronizingMessageSource.setScanner()了解更多信息。 此外,您现在可以将AbstractInboundFileSynchronizingMessageSourceWatchService-基于DirectoryScanner通过使用setUseWatchService()选择。 它还配置为所有WatchEventType实例对本地目录中的任何修改做出反应。 前面显示的重新处理示例基于FileReadingMessageSource.WatchServiceDirectoryScanner执行ResettableFileListFilter.remove()删除文件时 (StandardWatchEventKinds.ENTRY_DELETE) 从本地目录中。 看WatchServiceDirectoryScanner了解更多信息。spring-doc.cadn.net.cn

使用 Java 配置进行配置

以下 Spring Boot 应用程序显示了如何使用 Java 配置配置入站适配器的示例:spring-doc.cadn.net.cn

@SpringBootApplication
public class FtpJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(FtpJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
        sf.setHost("localhost");
        sf.setPort(port);
        sf.setUsername("foo");
        sf.setPassword("foo");
        sf.setTestSession(true);
        return new CachingSessionFactory<FTPFile>(sf);
    }

    @Bean
    public FtpInboundFileSynchronizer ftpInboundFileSynchronizer() {
        FtpInboundFileSynchronizer fileSynchronizer = new FtpInboundFileSynchronizer(ftpSessionFactory());
        fileSynchronizer.setDeleteRemoteFiles(false);
        fileSynchronizer.setRemoteDirectory("foo");
        fileSynchronizer.setFilter(new FtpSimplePatternFileListFilter("*.xml"));
        return fileSynchronizer;
    }

    @Bean
    @InboundChannelAdapter(channel = "ftpChannel", poller = @Poller(fixedDelay = "5000"))
    public MessageSource<File> ftpMessageSource() {
        FtpInboundFileSynchronizingMessageSource source =
                new FtpInboundFileSynchronizingMessageSource(ftpInboundFileSynchronizer());
        source.setLocalDirectory(new File("ftp-inbound"));
        source.setAutoCreateLocalDirectory(true);
        source.setLocalFilter(new AcceptOnceFileListFilter<File>());
        source.setMaxFetchSize(1);
        return source;
    }

    @Bean
    @ServiceActivator(inputChannel = "ftpChannel")
    public MessageHandler handler() {
        return new MessageHandler() {

            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                System.out.println(message.getPayload());
            }

        };
    }

}

使用 Java DSL 进行配置

以下 Spring Boot 应用程序显示了如何使用 Java DSL 配置入站适配器的示例:spring-doc.cadn.net.cn

@SpringBootApplication
public class FtpJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(FtpJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    public IntegrationFlow ftpInboundFlow() {
        return IntegrationFlow
            .from(Ftp.inboundAdapter(this.ftpSessionFactory)
                    .preserveTimestamp(true)
                    .remoteDirectory("foo")
                    .regexFilter(".*\\.txt$")
                    .localFilename(f -> f.toUpperCase() + ".a")
                    .localDirectory(new File("d:\\ftp_files")),
                e -> e.id("ftpInboundAdapter")
                    .autoStartup(true)
                    .poller(Pollers.fixedDelay(5000)))
            .handle(m -> System.out.println(m.getPayload()))
            .get();
    }
}

处理不完整的数据

FtpSystemMarkerFilePresentFileListFilter用于过滤远程系统上没有相应标记文件的远程文件。 有关配置信息,请参阅 Javadoc(并浏览到父类)。spring-doc.cadn.net.cn

FTP 流式入站通道适配器

版本 4.3 引入了流式入站通道适配器。 此适配器生成有效负载类型为InputStream,让文件在不写入 本地文件系统。 由于会话保持打开状态,因此当文件已打开时,使用应用程序负责关闭会话 消耗。 会话在closeableResource标头 (IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE). 标准框架组件,例如FileSplitterStreamTransformer,自动关闭会话。 有关这些组件的更多信息,请参阅文件拆分器和流转换器。 以下示例演示如何配置inbound-streaming-channel-adapter:spring-doc.cadn.net.cn

<int-ftp:inbound-streaming-channel-adapter id="ftpInbound"
            channel="ftpChannel"
            session-factory="sessionFactory"
            filename-pattern="*.txt"
            filename-regex=".*\.txt"
            filter="filter"
            filter-expression="@myFilterBean.check(#root)"
            remote-file-separator="/"
            comparator="comparator"
            max-fetch-size="1"
            remote-directory-expression="'foo/bar'">
        <int:poller fixed-rate="1000" />
</int-ftp:inbound-streaming-channel-adapter>

只有其中一个filename-pattern,filename-regex,filterfilter-expression是允许的。spring-doc.cadn.net.cn

从 5.0 版开始,默认情况下,FtpStreamingMessageSource适配器可防止远程文件的重复FtpPersistentAcceptOnceFileListFilter基于内存中的SimpleMetadataStore. 默认情况下,此过滤器也与文件名模式(或正则表达式)一起应用。 如果需要允许重复,可以使用AcceptAllFileListFilter. 任何其他用例都可以通过CompositeFileListFilter(或ChainFileListFilter). Java 配置(在文档后面)显示了一种在处理后删除远程文件以避免重复的技术。

有关FtpPersistentAcceptOnceFileListFilter及其使用方式,请参阅远程持久文件列表过滤器spring-doc.cadn.net.cn

使用max-fetch-size属性来限制在需要获取时每次轮询时获取的文件数量。 将其设置为1并在集群环境中运行时使用持久过滤器。 有关更多信息,请参阅入站通道适配器:控制远程文件获取spring-doc.cadn.net.cn

适配器将远程目录和文件名放在FileHeaders.REMOTE_DIRECTORYFileHeaders.REMOTE_FILE标头。 从 5.0 版开始,FileHeaders.REMOTE_FILE_INFOheader 提供额外的远程文件信息(默认以 JSON 表示)。 如果您将fileInfoJson属性FtpStreamingMessageSourcefalse,标头包含一个FtpFileInfo对象。 这FTPFile可以使用FtpFileInfo.getFileInfo()方法。 这fileInfoJson属性在使用 XML 配置时不可用,但您可以通过注入FtpStreamingMessageSource到您的配置类之一。 另请参阅远程文件信息spring-doc.cadn.net.cn

从 5.1 版开始,泛型类型comparatorFTPFile. 以前,它是AbstractFileInfo<FTPFile>. 这是因为排序现在是在处理的早期执行的,然后再筛选和应用maxFetch.spring-doc.cadn.net.cn

使用 Java 配置进行配置

以下 Spring Boot 应用程序显示了如何使用 Java 配置配置入站适配器的示例:spring-doc.cadn.net.cn

@SpringBootApplication
public class FtpJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(FtpJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    @InboundChannelAdapter(channel = "stream")
    public MessageSource<InputStream> ftpMessageSource() {
        FtpStreamingMessageSource messageSource = new FtpStreamingMessageSource(template());
        messageSource.setRemoteDirectory("ftpSource/");
        messageSource.setFilter(new AcceptAllFileListFilter<>());
        messageSource.setMaxFetchSize(1);
        return messageSource;
    }

    @Bean
    @Transformer(inputChannel = "stream", outputChannel = "data")
    public org.springframework.integration.transformer.Transformer transformer() {
        return new StreamTransformer("UTF-8");
    }

    @Bean
    public FtpRemoteFileTemplate template() {
        return new FtpRemoteFileTemplate(ftpSessionFactory());
    }

    @ServiceActivator(inputChannel = "data", adviceChain = "after")
    @Bean
    public MessageHandler handle() {
        return System.out::println;
    }

    @Bean
    public ExpressionEvaluatingRequestHandlerAdvice after() {
        ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
        advice.setOnSuccessExpression(
                "@template.remove(headers['file_remoteDirectory'] + headers['file_remoteFile'])");
        advice.setPropagateEvaluationFailures(true);
        return advice;
    }

}

请注意,在此示例中,转换器下游的消息处理程序具有advice在处理后删除远程文件。spring-doc.cadn.net.cn

入站通道适配器:轮询多个服务器和目录

从 5.0.7 版本开始,RotatingServerAdvice可用;当配置为轮询器通知时,入站适配器可以轮询多个服务器和目录。 配置通知并将其正常添加到轮询器的通知链中。 一个DelegatingSessionFactory用于选择服务器,请参阅委托会话工厂了解更多信息。 通知配置由以下列表组成RotationPolicy.KeyDirectory对象。spring-doc.cadn.net.cn

示例
@Bean
public RotatingServerAdvice advice() {
    List<RotationPolicy.KeyDirectory> keyDirectories = new ArrayList<>();
    keyDirectories.add(new RotationPolicy.KeyDirectory("one", "foo"));
    keyDirectories.add(new RotationPolicy.KeyDirectory("one", "bar"));
    keyDirectories.add(new RotationPolicy.KeyDirectory("two", "baz"));
    keyDirectories.add(new RotationPolicy.KeyDirectory("two", "qux"));
    keyDirectories.add(new RotationPolicy.KeyDirectory("three", "fiz"));
    keyDirectories.add(new RotationPolicy.KeyDirectory("three", "buz"));
    return new RotatingServerAdvice(delegatingSf(), keyDirectories);
}

此建议将轮询目录foo在服务器上one直到没有新文件存在,然后移动到目录bar然后是目录baz在服务器上two等。spring-doc.cadn.net.cn

可以使用fair构造函数 arg:spring-doc.cadn.net.cn

公平
@Bean
public RotatingServerAdvice advice() {
    ...
    return new RotatingServerAdvice(delegatingSf(), keyDirectories, true);
}

在这种情况下,通知将移动到下一个服务器/目录,而不管上一个轮询是否返回了文件。spring-doc.cadn.net.cn

或者,您可以提供自己的RotationPolicy要根据需要重新配置消息源,请执行以下作:spring-doc.cadn.net.cn

政策
public interface RotationPolicy {

    void beforeReceive(MessageSource<?> source);

    void afterReceive(boolean messageReceived, MessageSource<?> source);

}
习惯
@Bean
public RotatingServerAdvice advice() {
    return new RotatingServerAdvice(myRotationPolicy());
}

local-filename-generator-expression属性 (localFilenameGeneratorExpression)现在可以包含#remoteDirectory变量。 这允许从不同目录检索到的文件下载到本地的类似目录:spring-doc.cadn.net.cn

@Bean
public IntegrationFlow flow() {
    return IntegrationFlow.from(Ftp.inboundAdapter(sf())
                    .filter(new FtpPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), "rotate"))
                    .localDirectory(new File(tmpDir))
                    .localFilenameExpression("#remoteDirectory + T(java.io.File).separator + #root")
                    .remoteDirectory("."),
                e -> e.poller(Pollers.fixedDelay(1).advice(advice())))
            .channel(MessageChannels.queue("files"))
            .get();
}
不要配置TaskExecutor使用此建议时对轮询者;有关详细信息,请参阅消息源的条件轮询器。

入站通道适配器:控制远程文件获取

配置入站通道适配器时,应考虑两个属性。max-messages-per-poll与所有轮询器一样,可用于限制每次轮询时发出的消息数(如果准备就绪的消息超过配置值)。max-fetch-size(从 5.0 版开始)可以限制一次从远程服务器检索的文件数量。spring-doc.cadn.net.cn

以下方案假定启动状态为空的本地目录:spring-doc.cadn.net.cn

  • max-messages-per-poll=2max-fetch-size=1:适配器获取一个文件,发出它,获取下一个文件,发出它,然后休眠,直到下一次轮询。spring-doc.cadn.net.cn

  • max-messages-per-poll=2max-fetch-size=2):适配器获取两个文件,然后发出每个文件。spring-doc.cadn.net.cn

  • max-messages-per-poll=2max-fetch-size=4:适配器最多提取四个文件(如果可用)并发出前两个文件(如果至少有两个)。 接下来的两个文件将在下一次轮询时发出。spring-doc.cadn.net.cn

  • max-messages-per-poll=2max-fetch-size未指定:适配器获取所有远程文件并发出前两个文件(如果至少有两个)。 后续文件在后续轮询(一次两个)时发出。 当所有文件都被使用时,将再次尝试远程获取,以选取任何新文件。spring-doc.cadn.net.cn

当您部署应用程序的多个实例时,我们建议将max-fetch-size,以避免一个实例“抓取”所有文件并使其他实例饥饿。

另一种用途max-fetch-size是如果您想停止获取远程文件,但继续处理已获取的文件。 设置maxFetchSize属性MessageSource(以编程方式,使用 JMX 或控制总线)有效地阻止适配器获取更多文件,但允许轮询器继续为先前获取的文件发出消息。 如果在属性更改时轮询器处于活动状态,则更改将在下一次轮询时生效。spring-doc.cadn.net.cn

从 5.1 版开始,同步器可以为Comparator<FTPFile>. 这在限制使用maxFetchSize.spring-doc.cadn.net.cn

FTP 出站通道适配器

FTP 出站通道适配器依赖于MessageHandler连接到 FTP 服务器并为它在传入消息的有效负载中接收的每个文件启动 FTP 传输的实现。 它还支持一个文件的多种表示形式,因此您不仅限于java.io.File-类型有效负载。 FTP 出站通道适配器支持以下有效负载:spring-doc.cadn.net.cn

以下示例演示如何配置outbound-channel-adapter:spring-doc.cadn.net.cn

<int-ftp:outbound-channel-adapter id="ftpOutbound"
    channel="ftpChannel"
    session-factory="ftpSessionFactory"
    charset="UTF-8"
    remote-file-separator="/"
    auto-create-directory="true"
    remote-directory-expression="headers['remote_dir']"
    temporary-remote-directory-expression="headers['temp_remote_dir']"
    filename-generator="fileNameGenerator"
    use-temporary-filename="true"
    chmod="600"
    mode="REPLACE"/>

上述配置显示了如何使用outbound-channel-adapter元素,同时还为各种属性提供值,例如filename-generator(实现o.s.i.file.FileNameGeneratorstrategy 接口),对session-factory和其他属性。 您还可以看到一些示例*expression允许您使用 SpEL 配置设置的属性,例如remote-directory-expression,temporary-remote-directory-expressionremote-filename-generator-expression(SpEL 的替代方案filename-generator,如上例所示)。 与任何允许使用 SpEL 的组件一样,可以通过 'payload' 和 'headers' 变量访问有效负载和消息 Headers。 有关可用属性的更多详细信息,请参阅架构spring-doc.cadn.net.cn

默认情况下,如果未指定文件名生成器,Spring Integration 使用o.s.i.file.DefaultFileNameGenerator.DefaultFileNameGenerator根据file_name标头(如果存在)在MessageHeaders,或者,如果消息的有效负载已经是java.io.File,则使用该文件的原始名称。
定义某些值(例如remote-directory) 可能依赖于平台或 FTP 服务器。 例如,正如 https://forum.spring.io/showthread.php?p=333478&posted=1#post333478 上所报告的那样,在某些平台上,您必须在目录定义的末尾添加斜杠(例如,remote-directory="/thing1/thing2/"而不是remote-directory="/thing1/thing2").

从 4.1 版开始,您可以指定mode传输文件时。 默认情况下,将覆盖现有文件。 模式由FileExistsMode枚举,其中包括以下值:spring-doc.cadn.net.cn

IGNOREFAIL不要传输文件。FAIL导致抛出异常,而IGNORE静默忽略传输(尽管DEBUG生成日志条目)。spring-doc.cadn.net.cn

5.2 版引入了chmod属性,可用于在上传后更改远程文件权限。 您可以使用传统的 Unix 八进制格式(例如600仅允许文件所有者读写)。 使用 java 配置适配器时,您可以使用setChmodOctal("600")setChmod(0600). 仅当您的 FTP 服务器支持SITE CHMOD子命令。spring-doc.cadn.net.cn

避免部分写入的文件

处理文件传输时出现的常见问题之一是处理部分文件的可能性。 也就是说,文件可能会在传输实际完成之前出现在文件系统中。spring-doc.cadn.net.cn

为了解决这个问题,Spring Integration FTP 适配器使用一种通用算法:文件以临时名称传输,然后在完全传输后重命名。spring-doc.cadn.net.cn

默认情况下,正在传输的每个文件都显示在文件系统中,并带有一个附加后缀,默认情况下,该后缀为.writing. 您可以通过设置temporary-file-suffix属性。spring-doc.cadn.net.cn

但是,在某些情况下,您可能不想使用此技术(例如,如果服务器不允许重命名文件)。 对于这种情况,您可以通过设置use-temporary-file-namefalse(默认值为true). 当此属性为false,则该文件是用其最终名称写入的,并且使用应用程序需要一些其他机制来检测文件是否已完全上传,然后才能访问它。spring-doc.cadn.net.cn

使用 Java 配置进行配置

以下 Spring Boot 应用程序显示了如何使用 Java 配置配置出站适配器的示例:spring-doc.cadn.net.cn

@SpringBootApplication
@IntegrationComponentScan
public class FtpJavaApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                    new SpringApplicationBuilder(FtpJavaApplication.class)
                        .web(false)
                        .run(args);
        MyGateway gateway = context.getBean(MyGateway.class);
        gateway.sendToFtp(new File("/foo/bar.txt"));
    }

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
        sf.setHost("localhost");
        sf.setPort(port);
        sf.setUsername("foo");
        sf.setPassword("foo");
        sf.setTestSession(true);
        return new CachingSessionFactory<FTPFile>(sf);
    }

    @Bean
    @ServiceActivator(inputChannel = "ftpChannel")
    public MessageHandler handler() {
        FtpMessageHandler handler = new FtpMessageHandler(ftpSessionFactory());
        handler.setRemoteDirectoryExpressionString("headers['remote-target-dir']");
        handler.setFileNameGenerator(new FileNameGenerator() {

            @Override
            public String generateFileName(Message<?> message) {
                 return "handlerContent.test";
            }

        });
        return handler;
    }

    @MessagingGateway
    public interface MyGateway {

         @Gateway(requestChannel = "toFtpChannel")
         void sendToFtp(File file);

    }
}

使用 Java DSL 进行配置

以下 Spring Boot 应用程序显示了如何使用 Java DSL 配置出站适配器的示例:spring-doc.cadn.net.cn

@SpringBootApplication
@IntegrationComponentScan
public class FtpJavaApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =
            new SpringApplicationBuilder(FtpJavaApplication.class)
                .web(false)
                .run(args);
        MyGateway gateway = context.getBean(MyGateway.class);
        gateway.sendToFtp(new File("/foo/bar.txt"));
    }

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
        sf.setHost("localhost");
        sf.setPort(port);
        sf.setUsername("foo");
        sf.setPassword("foo");
        sf.setTestSession(true);
        return new CachingSessionFactory<FTPFile>(sf);
    }

    @Bean
    public IntegrationFlow ftpOutboundFlow() {
        return IntegrationFlow.from("toFtpChannel")
                .handle(Ftp.outboundAdapter(ftpSessionFactory(), FileExistsMode.FAIL)
                        .useTemporaryFileName(false)
                        .fileNameExpression("headers['" + FileHeaders.FILENAME + "']")
                        .remoteDirectory(this.ftpServer.getTargetFtpDirectory().getName())
                ).get();
    }

    @MessagingGateway
    public interface MyGateway {

         @Gateway(requestChannel = "toFtpChannel")
         void sendToFtp(File file);

    }

}

FTP 出站网关

FTP 出站网关提供一组有限的命令来与远程 FTP 或 FTPS 服务器交互。 支持的命令包括:spring-doc.cadn.net.cn

使用ls命令

ls列出远程文件并支持以下选项:spring-doc.cadn.net.cn

此外,还提供了文件名过滤,其方式与inbound-channel-adapter. 请参阅 FTP 入站通道适配器spring-doc.cadn.net.cn

ls作是文件名列表或FileInfo对象。 这些对象提供修改时间、权限和其他详细信息等信息。spring-doc.cadn.net.cn

远程目录ls命令在file_remoteDirectory页眉。spring-doc.cadn.net.cn

使用递归选项 (-R)、fileName包括任何子目录元素,表示文件的相对路径(相对于远程目录)。 如果-dirs选项,则每个递归目录也作为列表中的元素返回。 在这种情况下,建议您不要使用-1选项,因为您将无法区分文件和目录,您可以使用FileInfo对象。spring-doc.cadn.net.cn

从 4.3 版开始,FtpSession支持null对于list()listNames()方法。 因此,您可以省略expression属性。 为方便起见,Java 配置有两个构造函数,它们没有expression论点。 或LS,NLST,PUTMPUT命令null根据 FTP 协议,被视为客户端工作目录。 所有其他命令必须与expression根据请求消息评估远程路径。 您可以使用FTPClient.changeWorkingDirectory()函数扩展DefaultFtpSessionFactory并实现postProcessClientAfterConnect()回调。spring-doc.cadn.net.cn

使用nlst命令

版本 5 引入了对nlst命令。spring-doc.cadn.net.cn

nlst列出远程文件名,仅支持一个选项:spring-doc.cadn.net.cn

nlst作是文件名的列表。spring-doc.cadn.net.cn

远程目录nlst命令在file_remoteDirectory页眉。spring-doc.cadn.net.cn

-1选项的ls命令,它使用LIST命令,则nlst命令发送一个NLST命令发送到目标 FTP 服务器。 当服务器不支持LIST(例如,由于安全限制)。 结果nlst作是名称,没有其他细节。 因此,框架无法确定实体是否是目录,例如执行过滤或递归列表。spring-doc.cadn.net.cn

使用get命令

get检索远程文件。 它支持以下选项:spring-doc.cadn.net.cn

file_remoteDirectory标头提供远程目录名称,而file_remoteFileheader 提供文件名。spring-doc.cadn.net.cn

get作是一个File表示检索到的文件的对象或InputStream当您使用-stream选择。 这-stream选项允许将文件检索为流。 对于文本文件,一个常见的用例是将此作与文件拆分器流转换器相结合。 当将远程文件作为流使用时,您负责关闭Session在流被消耗后。 为方便起见,该SessioncloseableResource标头,您可以使用方便的方法访问它IntegrationMessageHeaderAccessor以下示例显示如何使用方便方法:spring-doc.cadn.net.cn

Closeable closeable = new IntegrationMessageHeaderAccessor(message).getCloseableResource();
if (closeable != null) {
    closeable.close();
}

文件拆分器和流转换器等框架组件在数据传输后自动关闭会话。spring-doc.cadn.net.cn

以下示例演示如何将文件作为流使用:spring-doc.cadn.net.cn

<int-ftp:outbound-gateway session-factory="ftpSessionFactory"
                            request-channel="inboundGetStream"
                            command="get"
                            command-options="-stream"
                            expression="payload"
                            remote-directory="ftpTarget"
                            reply-channel="stream" />

<int-file:splitter input-channel="stream" output-channel="lines" />
如果您在自定义组件中使用输入流,则必须关闭Session. 您可以在自定义代码中执行此作,也可以通过将消息副本路由到service-activator并使用 SpEL,如以下示例所示:
<int:service-activator input-channel="closeSession"
    expression="headers['closeableResource'].close()" />

使用mget命令

mget根据模式检索多个远程文件,并支持以下选项:spring-doc.cadn.net.cn

mget作是一个List<File>对象(即ListFile对象,每个对象代表一个检索到的文件)。spring-doc.cadn.net.cn

从 5.0 版开始,如果FileExistsModeIGNORE,则输出消息的有效负载不再包含由于文件已存在而未获取的文件。 以前,该列表包含所有文件,包括那些已经存在的文件。

用于确定远程路径的表达式应产生以- 例如somedir/将获取somedir.spring-doc.cadn.net.cn

从 5.0 版本开始,递归mget,结合新的FileExistsMode.REPLACE_IF_MODIFIEDmode,可用于在本地定期同步整个远程目录树。 此模式将本地文件的上次修改时间戳替换为远程时间戳,无论-P(保留时间戳)选项。spring-doc.cadn.net.cn

使用递归 (-R)

该模式将被忽略,并被假定。 默认情况下,检索整个远程树。 但是,可以通过提供*FileListFilter. 树中的目录也可以以这种方式过滤。 一个FileListFilter可通过引用提供,由filename-pattern,或通过filename-regex属性。 例如filename-regex="(subDir|.*1.txt)"检索所有以1.txt在远程目录中,并且subDirchild 目录。 但是,下一个示例显示了一种替代方法,即 5.0 版提供了该替代方案。spring-doc.cadn.net.cn

如果过滤了子目录,则不会对该子目录执行其他遍历。spring-doc.cadn.net.cn

-dirs选项不允许(递归mget使用递归ls获取目录树,因此目录本身不能包含在列表中)。spring-doc.cadn.net.cn

通常,您可以使用#remoteDirectory变量local-directory-expression以便远程目录结构在本地保留。spring-doc.cadn.net.cn

持久文件列表过滤器现在具有布尔属性forRecursion. 将此属性设置为true,也设置alwaysAcceptDirectories,这意味着出站网关上的递归作 (lsmget) 现在每次都会遍历完整的目录树。 这是为了解决未检测到目录树深处更改的问题。 另外forRecursion=true导致文件的完整路径用作元数据存储键;这解决了如果具有相同名称的文件多次出现在不同目录中,则过滤器无法正常工作的问题。 重要提示:这意味着对于顶级目录下的文件,将找不到持久元数据存储中的现有密钥。 因此,该属性是false默认情况下;这可能会在将来的版本中更改。spring-doc.cadn.net.cn

从 5.0 版开始,FtpSimplePatternFileListFilterFtpRegexPatternFileListFilter可以通过将alwaysAcceptDirectories属性设置为true. 这样做允许简单模式的递归,如以下示例所示:spring-doc.cadn.net.cn

<bean id="starDotTxtFilter"
        class="org.springframework.integration.ftp.filters.FtpSimplePatternFileListFilter">
    <constructor-arg value="*.txt" />
    <property name="alwaysAcceptDirectories" value="true" />
</bean>

<bean id="dotStarDotTxtFilter"
            class="org.springframework.integration.ftp.filters.FtpRegexPatternFileListFilter">
    <constructor-arg value="^.*\.txt$" />
    <property name="alwaysAcceptDirectories" value="true" />
</bean>

定义了前面示例中的过滤器后,可以通过将filter网关上的属性。spring-doc.cadn.net.cn

使用put命令

put命令将文件发送到远程服务器。 消息的有效负载可以是java.io.File一个byte[]String. 一个remote-filename-generator(或表达式)用于命名远程文件。 其他可用属性包括remote-directory,temporary-remote-directory,以及他们的*-expression等价物:use-temporary-file-nameauto-create-directory. 有关更多信息,请参阅架构文档。spring-doc.cadn.net.cn

put作是一个String表示传输后服务器上文件的完整路径。spring-doc.cadn.net.cn

5.2 版引入了chmod属性,该属性在上传后更改远程文件权限。 您可以使用传统的 Unix 八进制格式(例如600仅允许文件所有者读写)。 使用 java 配置适配器时,您可以使用setChmod(0600). 仅当您的 FTP 服务器支持SITE CHMOD子命令。spring-doc.cadn.net.cn

使用mput命令

mput将多个文件发送到服务器,并且仅支持一个选项:spring-doc.cadn.net.cn

  • -R:递归的。 发送目录及其子目录中的所有文件(可能已过滤)。spring-doc.cadn.net.cn

消息有效负载必须是java.io.File(或String) 表示本地目录。 从 5.1 版本开始,集合FileString也受支持。spring-doc.cadn.net.cn

此命令支持与put命令. 此外,可以使用以下选项之一过滤本地目录中的文件mput-pattern,mput-regex,mput-filtermput-filter-expression. 过滤器与递归一起工作,只要子目录本身通过过滤器即可。 未通过过滤器的子目录不会递归。spring-doc.cadn.net.cn

mput作是一个List<String>对象(即List传输产生的远程文件路径)。spring-doc.cadn.net.cn

5.2 版引入了chmod属性,允许您在上传后更改远程文件权限。 您可以使用传统的 Unix 八进制格式(例如600仅允许文件所有者读写)。 使用 Java 配置适配器时,您可以使用setChmodOctal("600")setChmod(0600). 仅当您的 FTP 服务器支持SITE CHMOD子命令。spring-doc.cadn.net.cn

使用rm命令

rm命令删除文件。spring-doc.cadn.net.cn

rm命令没有选项。spring-doc.cadn.net.cn

rm作是Boolean.TRUE如果删除成功或Boolean.FALSE否则。 这file_remoteDirectoryheader 提供远程目录,而file_remoteFileheader 提供文件名。spring-doc.cadn.net.cn

使用mv命令

mv命令移动文件。spring-doc.cadn.net.cn

mv命令没有选项。spring-doc.cadn.net.cn

expression属性定义“from”路径,而rename-expression属性定义“to”路径。 默认情况下,rename-expressionheaders['file_renameTo']. 此表达式的计算结果不得为 null 或空String. 如有必要,将创建任何必要的远程目录。 结果消息的有效负载为Boolean.TRUE. 这file_remoteDirectoryheader 提供原始远程目录,并且file_remoteFileheader 提供文件名。 新路径位于file_renameTo页眉。spring-doc.cadn.net.cn

从 5.5.6 版本开始,remoteDirectoryExpression可用于mv为了方便起见,命令。 如果“from”文件不是完整的文件路径,则remoteDirectoryExpression用作远程目录。 这同样适用于“to”文件,例如,如果任务只是重命名某个目录中的远程文件。spring-doc.cadn.net.cn

有关 FTP 出站网关命令的其他信息

getmget命令支持local-filename-generator-expression属性。 它定义了一个 SpEL 表达式,用于在传输期间生成本地文件的名称。 评估上下文的根对象是请求消息。 这remoteFileName变量,这对于mget,也可以使用 - 例如local-filename-generator-expression="#remoteFileName.toUpperCase() + headers.something".spring-doc.cadn.net.cn

getmget命令支持local-directory-expression属性。 它定义了一个 SpEL 表达式,用于在传输期间生成本地目录的名称。 评估上下文的根对象是请求消息 but。 这remoteDirectory变量,这对于mget,也可用 — 例如:local-directory-expression="'/tmp/local/' + #remoteDirectory.toUpperCase() + headers.something". 此属性与local-directory属性。spring-doc.cadn.net.cn

对于所有命令,网关的“expression”属性提供命令作用的路径。 对于mget命令,则表达式的计算结果可能为 '',表示检索所有文件,或 'somedirectory/',依此类推。spring-doc.cadn.net.cn

以下示例显示了为ls命令:spring-doc.cadn.net.cn

<int-ftp:outbound-gateway id="gateway1"
    session-factory="ftpSessionFactory"
    request-channel="inbound1"
    command="ls"
    command-options="-1"
    expression="payload"
    reply-channel="toSplitter"/>

发送到toSplitterchannel 是String每个对象都包含文件名。 如果command-options属性被省略,它FileInfo对象。 它使用空格分隔的选项,例如command-options="-1 -dirs -links".spring-doc.cadn.net.cn

从 4.2 版开始,GET,MGET,PUTMPUT命令支持FileExistsMode属性 (mode使用命名空间支持时)。 这会影响本地文件存在时的行为 (GETMGET) 或远程文件存在 (PUTMPUT). 支持的模式包括REPLACE,APPEND,FAILIGNORE. 为了向后兼容,默认模式PUTMPUT作是REPLACE. 为GETMGET作,默认值为FAIL.spring-doc.cadn.net.cn

从 5.0 版开始,setWorkingDirExpression() (working-dir-expression在 XML 中)选项在FtpOutboundGateway (<int-ftp:outbound-gateway>在 XML 中)。 它允许您在运行时更改客户端工作目录。 根据请求消息评估表达式。 每次网关作后,都会恢复以前的工作目录。spring-doc.cadn.net.cn

使用 Java 配置进行配置

以下 Spring Boot 应用程序显示了如何使用 Java 配置配置出站网关的示例:spring-doc.cadn.net.cn

@SpringBootApplication
public class FtpJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(FtpJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
        sf.setHost("localhost");
        sf.setPort(port);
        sf.setUsername("foo");
        sf.setPassword("foo");
        sf.setTestSession(true);
        return new CachingSessionFactory<FTPFile>(sf);
    }

    @Bean
    @ServiceActivator(inputChannel = "ftpChannel")
    public MessageHandler handler() {
        FtpOutboundGateway ftpOutboundGateway =
                          new FtpOutboundGateway(ftpSessionFactory(), "ls", "'my_remote_dir/'");
        ftpOutboundGateway.setOutputChannelName("lsReplyChannel");
        return ftpOutboundGateway;
    }

}

使用 Java DSL 进行配置

以下 Spring Boot 应用程序显示了如何使用 Java DSL 配置出站网关的示例:spring-doc.cadn.net.cn

@SpringBootApplication
public class FtpJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(FtpJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
        sf.setHost("localhost");
        sf.setPort(port);
        sf.setUsername("foo");
        sf.setPassword("foo");
        sf.setTestSession(true);
        return new CachingSessionFactory<FTPFile>(sf);
    }

    @Bean
    public FtpOutboundGatewaySpec ftpOutboundGateway() {
        return Ftp.outboundGateway(ftpSessionFactory(),
            AbstractRemoteFileOutboundGateway.Command.MGET, "payload")
            .options(AbstractRemoteFileOutboundGateway.Option.RECURSIVE)
            .regexFileNameFilter("(subFtpSource|.*1.txt)")
            .localDirectoryExpression("'localDirectory/' + #remoteDirectory")
            .localFilenameExpression("#remoteFileName.replaceFirst('ftpSource', 'localTarget')");
    }

    @Bean
    public IntegrationFlow ftpMGetFlow(AbstractRemoteFileOutboundGateway<FTPFile> ftpOutboundGateway) {
        return f -> f
            .handle(ftpOutboundGateway)
            .channel(c -> c.queue("remoteFileOutputChannel"));
    }

}

出站网关部分成功 (mgetmput)

对多个文件执行作时(使用mgetmput),在传输一个或多个文件后一段时间可能会发生异常。 在这种情况下(从 4.2 版开始),一个PartialSuccessException被抛出。 以及通常的MessagingException属性 (failedMessagecause),则此异常具有两个附加属性:spring-doc.cadn.net.cn

这些属性允许您确定哪些文件已成功传输,哪些文件未成功传输。spring-doc.cadn.net.cn

在递归的情况下mputPartialSuccessException可能已经嵌套PartialSuccessException事件。spring-doc.cadn.net.cn

请考虑以下目录结构:spring-doc.cadn.net.cn

root/
|- file1.txt
|- subdir/
   | - file2.txt
   | - file3.txt
|- zoo.txt

如果异常发生在file3.txtPartialSuccessException由网关抛出derivedInputfile1.txt,subdirzoo.txtpartialResultsfile1.txt. 其cause是另一个PartialSuccessExceptionderivedInputfile2.txtfile3.txtpartialResultsfile2.txt.spring-doc.cadn.net.cn

FTP 会话缓存

从 Spring Integration 3.0 开始,默认情况下不再缓存会话。 这cache-sessions端点不再支持属性。您必须使用CachingSessionFactory(如下一个示例所示),如果希望缓存会话。

在 3.0 之前的版本中,默认情况下会自动缓存会话。 一个cache-sessions属性可用于禁用自动缓存,但该解决方案不提供配置其他会话缓存属性的方法。 例如,您无法限制创建的会话数。 为了支持该要求和其他配置选项,一个CachingSessionFactory被添加。 它提供了sessionCacheSizesessionWaitTimeout性能。 这sessionCacheSize属性控制工厂在其缓存中维护的活动会话数(默认值为无限制)。 如果sessionCacheSize已达到阈值,则任何获取另一个会话的尝试都会阻塞,直到其中一个缓存的会话变为可用或会话的等待时间到期(默认等待时间为Integer.MAX_VALUE). 这sessionWaitTimeout属性配置该值。spring-doc.cadn.net.cn

如果您希望缓存会话,请按照前面所述配置默认会话工厂,然后将其包装在CachingSessionFactory,您可以在其中提供这些附加属性。 以下示例显示了如何执行此作:spring-doc.cadn.net.cn

<bean id="ftpSessionFactory" class="o.s.i.ftp.session.DefaultFtpSessionFactory">
    <property name="host" value="localhost"/>
</bean>

<bean id="cachingSessionFactory" class="o.s.i.file.remote.session.CachingSessionFactory">
    <constructor-arg ref="ftpSessionFactory"/>
    <constructor-arg value="10"/>
    <property name="sessionWaitTimeout" value="1000"/>
</bean>

前面的示例显示了CachingSessionFactory使用sessionCacheSize设置为10sessionWaitTimeout设置为一秒(其值以毫秒为单位)。spring-doc.cadn.net.cn

从 Spring Integration 3.0 开始,CachingConnectionFactory提供一个resetCache()方法。 调用时,所有空闲会话都会立即关闭,正在使用的会话在返回到缓存时会关闭。 新的会话请求会根据需要建立新的会话。spring-doc.cadn.net.cn

从 5.1 版本开始,CachingSessionFactory有一个新属性testSession. 当为 true 时,将通过发送 NOOP 命令来测试会话,以确保它仍然处于活动状态;如果没有,它将从缓存中删除;如果缓存中没有活动会话,则会创建新会话。spring-doc.cadn.net.cn

RemoteFileTemplate

从 Spring Integration 3.0 开始,在FtpSession对象。 该模板提供了发送、检索的方法(作为InputStream)、删除和重命名文件。 此外,一个execute方法允许调用者在会话上执行多个作。 在所有情况下,模板都会负责可靠地关闭会话。 有关更多信息,请参阅Javadoc 的RemoteFileTemplate. FTP 有一个子类:FtpRemoteFileTemplate.spring-doc.cadn.net.cn

4.1 版添加了其他方法,包括getClientInstance(),提供对基础FTPClient从而使您可以访问低级 API。spring-doc.cadn.net.cn

并非所有 FTP 服务器都正确实现STAT <path>命令。 有些路径返回不存在的路径的正结果。 这NLST当路径是文件并且它存在时,命令会可靠地返回名称。 但是,这不支持检查空目录是否存在,因为NLST当路径为目录时,始终返回一个空列表。 由于模板不知道路径是否代表目录,因此当路径似乎不存在时,它必须执行额外的检查(当使用NLST). 这增加了开销,需要向服务器发出多个请求。 从 4.1.9 版开始,FtpRemoteFileTemplate提供FtpRemoteFileTemplate.ExistsMode属性,其中包含以下选项:spring-doc.cadn.net.cn

  • STAT:执行STATFTP 命令 (FTPClient.getStatus(path)) 检查路径是否存在。 这是默认设置,要求您的 FTP 服务器正确支持STAT命令(带有路径)。spring-doc.cadn.net.cn

  • NLST:执行NLSTFTP 命令 —FTPClient.listName(path). 如果要测试文件的完整路径,请使用此选项。 它不适用于空目录。spring-doc.cadn.net.cn

  • NLST_AND_DIRS:执行NLST命令,如果它没有返回任何文件,则回退到一种技术,该技术通过使用FTPClient.changeWorkingDirectory(path). 看FtpSession.exists()了解更多信息。spring-doc.cadn.net.cn

由于我们知道FileExistsMode.FAILcase 总是只查找文件(而不是目录),我们安全地使用NLST模式的FtpMessageHandlerFtpOutboundGateway组件。spring-doc.cadn.net.cn

对于任何其他情况,请FtpRemoteFileTemplate可以扩展以在被覆盖的exist()方法。spring-doc.cadn.net.cn

从 5.0 版开始,新的RemoteFileOperations.invoke(OperationsCallback<F, T> action)方法可用。 此方法允许多个RemoteFileOperations调用在相同的、线程边界的范围内调用,Session. 当您需要执行RemoteFileTemplate作为一个工作单元。 例如AbstractRemoteFileOutboundGateway将其与mput命令实现,其中我们执行put对所提供目录中的每个文件进行作,并递归地对其子目录进行作。 有关更多信息,请参阅 Javadocspring-doc.cadn.net.cn

MessageSessionCallback

从 Spring Integration 4.2 开始,您可以使用MessageSessionCallback<F, T>使用<int-ftp:outbound-gateway/> (FtpOutboundGateway在 Java 中)对Session<FTPFile>使用requestMessage上下文。 它可用于任何非标准或低级 FTP作,并允许从集成流定义和功能接口 (Lambda) 实现注入进行访问,如以下示例所示:spring-doc.cadn.net.cn

@Bean
@ServiceActivator(inputChannel = "ftpChannel")
public MessageHandler ftpOutboundGateway(SessionFactory<FTPFile> sessionFactory) {
    return new FtpOutboundGateway(sessionFactory,
         (session, requestMessage) -> session.list(requestMessage.getPayload()));
}

另一个示例可能是对正在发送或检索的文件数据进行预处理或后处理。spring-doc.cadn.net.cn

使用 XML 配置时,<int-ftp:outbound-gateway/>提供一个session-callback属性,让您指定MessageSessionCallbackbean 名称。spring-doc.cadn.net.cn

session-callbackcommandexpression属性。 使用 Java 配置时,不同的构造函数在FtpOutboundGateway类。

Apache Mina FTP 服务器事件

ApacheMinaFtplet,在 5.2 版中添加,监听某些 Apache Mina FTP 服务器事件并将它们发布为ApplicationEvent可以由任何ApplicationListener@EventListenerbean 方法或事件入站通道适配器spring-doc.cadn.net.cn

目前,支持的事件包括:spring-doc.cadn.net.cn

其中每一个都是ApacheMinaFtpEvent;您可以配置单个侦听器来接收所有事件类型。 这source每个事件的属性是FtpSession,您可以从中获取客户地址等信息;一个方便的getSession()方法。spring-doc.cadn.net.cn

会话打开/关闭以外的事件具有另一个属性FtpRequest它具有命令和参数等属性。spring-doc.cadn.net.cn

要使用侦听器(必须是 Spring bean)配置服务器,请将其添加到服务器工厂:spring-doc.cadn.net.cn

FtpServerFactory serverFactory = new FtpServerFactory();
...
ListenerFactory factory = new ListenerFactory();
...
serverFactory.addListener("default", factory.createListener());
serverFactory.setFtplets(new HashMap<>(Collections.singletonMap("springFtplet", apacheMinaFtpletBean)));
server = serverFactory.createServer();
server.start();

要使用 Spring Integration 事件适配器使用这些事件:spring-doc.cadn.net.cn

@Bean
public ApplicationEventListeningMessageProducer eventsAdapter() {
    ApplicationEventListeningMessageProducer producer =
        new ApplicationEventListeningMessageProducer();
    producer.setEventTypes(ApacheMinaFtpEvent.class);
    producer.setOutputChannel(eventChannel());
    return producer;
}

远程文件信息

从 5.2 版开始,FtpStreamingMessageSource (FTP 流式入站通道适配器),FtpInboundFileSynchronizingMessageSource (FTP 入站通道适配器)和 “read”命令FtpOutboundGateway (FTP 出站网关)在消息中提供其他标头以生成有关远程文件的信息:spring-doc.cadn.net.cn

由于FtpInboundFileSynchronizingMessageSource不会针对远程文件生成消息,但使用本地副本,AbstractInboundFileSynchronizer将有关远程文件的信息存储在MetadataStore(可以在外部配置)的 URI 样式 (protocol://host:port/remoteDirectory#remoteFileName) 在同步作期间。 此元数据由FtpInboundFileSynchronizingMessageSource轮询本地文件时。 删除本地文件时,建议删除其元数据条目。 这AbstractInboundFileSynchronizer提供一个removeRemoteFileMetadata()回调。 此外,还有一个setMetadataStorePrefix()用于元数据键。 建议将此前缀与MetadataStore-基于FileListFilter实现,当相同时MetadataStoreinstance 在这些组件之间共享,以避免条目覆盖,因为 filter 和AbstractInboundFileSynchronizer对元数据条目键使用相同的本地文件名。spring-doc.cadn.net.cn