SFTP 适配器

SFTP 适配器

Spring 集成支持通过 SFTP 进行文件传输作。spring-doc.cadn.net.cn

安全文件传输协议 (SFTP) 是一种网络协议,可让您通过任何可靠的流在 Internet 上的两台计算机之间传输文件。spring-doc.cadn.net.cn

SFTP 协议需要一个安全通道(如 SSH),并在整个 SFTP 会话中对客户端身份的可见性。spring-doc.cadn.net.cn

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

从版本 6.0 开始,过时的 JCraft JSch 客户端已被现代 Apache MINA SSHD 框架取代。 这导致框架组件发生了很多重大变化。 但是,在大多数情况下,这样的迁移隐藏在 Spring Integration API 后面。 最剧烈的变化发生在DefaultSftpSessionFactory它现在基于org.apache.sshd.client.SshClient并公开一些 if 的 configuration 属性。

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

Maven 系列
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-sftp</artifactId>
    <version>6.0.9</version>
</dependency>
Gradle
compile "org.springframework.integration:spring-integration-sftp:6.0.9"

要在 xml 配置中包含 SFTP 命名空间,请在 root 元素上包含以下属性:spring-doc.cadn.net.cn

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

SFTP 会话工厂

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

在配置 SFTP 适配器之前,必须配置 SFTP 会话工厂。 您可以使用常规 bean 定义配置 SFTP 会话工厂,如下例所示:spring-doc.cadn.net.cn

<beans:bean id="sftpSessionFactory"
    class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
    <beans:property name="host" value="localhost"/>
    <beans:property name="privateKey" value="classpath:META-INF/keys/sftpTest"/>
    <beans:property name="privateKeyPassphrase" value="springIntegration"/>
    <beans:property name="port" value="22"/>
    <beans:property name="user" value="kermit"/>
</beans:bean>

每次适配器从其SessionFactory,则会创建一个新的 SFTP 会话。 实际上,SFTP Session Factory 依赖于 Apache MINA SSHD 库来提供 SFTP 功能。spring-doc.cadn.net.cn

但是, Spring 集成还支持 SFTP 会话的缓存。 有关更多信息,请参阅 SFTP 会话缓存spring-doc.cadn.net.cn

SshClient支持通过与服务器的连接使用多个通道 (作)。 默认情况下, Spring 集成会话工厂为每个通道使用单独的物理连接。 从 Spring Integration 3.0 开始,你可以配置会话工厂(使用布尔构造函数 arg - defaultfalse) 使用与服务器的单个连接并创建多个SftpClient实例。spring-doc.cadn.net.cn

使用此功能时,必须将 session factory 包装在缓存 session factory 中,如下所述,以便在作完成时不会物理关闭连接。spring-doc.cadn.net.cn

如果重置缓存,则仅当最后一个通道关闭时,会话才会断开连接。spring-doc.cadn.net.cn

如果在新作获取会话时发现连接已断开连接,则会刷新连接。spring-doc.cadn.net.cn

现在您需要做的就是将此 SFTP 会话工厂注入到您的适配器中。spring-doc.cadn.net.cn

为 SFTP 会话工厂提供值的更实用的方法是使用 Spring 的属性占位符支持

配置属性

isSharedSession(constructor argument)::当true、单个SftpClient用于所有请求的SftpSession实例。 它默认为false.spring-doc.cadn.net.cn

sftpVersionSelector::一SftpVersionSelectorinstance 进行 SFTP 协议选择。 默认值为SftpVersionSelector.CURRENT.spring-doc.cadn.net.cn

host::要连接到的主机的 URL。 必填。spring-doc.cadn.net.cn

hostConfig::一org.apache.sshd.client.config.hosts.HostConfigEntry实例作为 user/host/port 选项的替代项。 可以使用代理跳转属性进行配置。spring-doc.cadn.net.cn

port::应通过其建立 SFTP 连接的端口。 如果未指定,此值默认为22. 如果指定,则此属性必须为正数。spring-doc.cadn.net.cn

user::要使用的远程用户。 必填。spring-doc.cadn.net.cn

knownHostsResource::一org.springframework.core.io.Resource用于主机密钥存储库。 资源的内容必须与 OpenSSH 的格式相同known_hosts文件,并且是必需的,如果allowUnknownKeys为 false。spring-doc.cadn.net.cn

password::用于对远程主机进行身份验证的密码。 如果未提供密码,则privateKeyproperty 是必需的。spring-doc.cadn.net.cn

privateKey::一org.springframework.core.io.Resource该 ID 表示用于对远程主机进行身份验证的私有密钥的位置。 如果privateKey未提供,则passwordproperty 是必需的。spring-doc.cadn.net.cn

privateKeyPassphrase::私钥的密码。 如果您将userInfo,privateKeyPassphrase不允许。 密码是从该对象获取的。 自选。spring-doc.cadn.net.cn

timeout::timeout 属性用作套接字超时参数,以及默认连接超时。 默认为0,这意味着不会发生超时。spring-doc.cadn.net.cn

allowUnknownKeys::设置为true以允许连接到具有未知(或更改)密钥的主机。 它的默认值是 'false'。 如果false,则预填充的knownHostsfile 是必需的。spring-doc.cadn.net.cn

userInteraction::A 定制org.apache.sshd.client.auth.keyboard.UserInteraction在身份验证期间使用。spring-doc.cadn.net.cn

委派 Session Factory

版本 4.2 引入了DelegatingSessionFactory,这允许在运行时选择实际的 session factory。 在调用 SFTP 端点之前,您可以调用setThreadKey()将 key 与当前线程相关联。 然后,该键用于查找要使用的实际会话工厂。 您可以通过调用clearThreadKey()使用后。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-sftp:outbound-gateway request-channel="c1" reply-channel="c2" ... />

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

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

SFTP 会话缓存

从 Spring 集成版本 3.0 开始,默认情况下不再缓存会话。 这cache-sessions属性。 如果您希望缓存会话,则必须使用CachingSessionFactory(请参阅下一个示例)。

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

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

<bean id="sftpSessionFactory"
    class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
    <property name="host" value="localhost"/>
</bean>

<bean id="cachingSessionFactory"
    class="org.springframework.integration.file.remote.session.CachingSessionFactory">
    <constructor-arg ref="sftpSessionFactory"/>
    <constructor-arg value="10"/>
    <property name="sessionWaitTimeout" value="1000"/>
</bean>

前面的示例创建了一个CachingSessionFactory及其sessionCacheSize设置为10及其sessionWaitTimeout设置为 1 秒(1000 毫秒)。spring-doc.cadn.net.cn

从 Spring Integration 版本 3.0 开始,CachingConnectionFactory提供resetCache()方法。 调用时,所有空闲会话将立即关闭,而正在使用的会话将在返回到缓存时关闭。 使用isSharedSession=true,则仅当最后一个通道关闭时,通道将关闭,并且共享会话才会关闭。 对会话的新请求会根据需要建立新会话。spring-doc.cadn.net.cn

从版本 5.1 开始,CachingSessionFactory具有新属性testSession. 如果为 true,则将通过执行REALPATH命令为空路径,以确保它仍然处于活动状态;否则,将从缓存中删除它;如果缓存中没有活动会话,则会创建一个新会话。spring-doc.cadn.net.cn

RemoteFileTemplate

Spring 集成版本 3.0 提供了对SftpSession对象。 该模板提供了用于发送、检索(作为InputStream)、删除和重命名文件。 此外,我们还提供了一个execute方法让调用方对会话运行多个作。 在所有情况下,模板都会可靠地关闭会话。 有关更多信息,请参阅Javadoc 的RemoteFileTemplateSFTP 有一个子类:SftpRemoteFileTemplate.spring-doc.cadn.net.cn

我们在版本 4.1 中添加了其他方法,包括getClientInstance(). 它提供对底层ChannelSftp,它允许访问低级 API。spring-doc.cadn.net.cn

版本 5.0 引入了RemoteFileOperations.invoke(OperationsCallback<F, T> action)方法。 此方法允许多个RemoteFileOperations调用在同一个线程绑定的范围内调用Session. 当您需要执行RemoteFileTemplate作为一个工作单元。 例如AbstractRemoteFileOutboundGateway将其与mputcommand 实现,其中我们执行put作,并递归地作其子目录。 有关更多信息,请参阅 Javadocspring-doc.cadn.net.cn

SFTP 入站通道适配器

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

<int-sftp:inbound-channel-adapter id="sftpAdapterAutoCreate"
              session-factory="sftpSessionFactory"
            channel="requestChannel"
            filename-pattern="*.txt"
            remote-directory="/foo/bar"
            preserve-timestamp="true"
            local-directory="file:target/foo"
            auto-create-local-directory="true"
            local-filename-generator-expression="#this.toUpperCase() + '.a'"
            scanner="myDirScanner"
            local-filter="myFilter"
            temporary-file-suffix=".writing"
            max-fetch-size="-1"
            delete-remote-files="false">
        <int:poller fixed-rate="1000"/>
</int-sftp:inbound-channel-adapter>

前面的配置示例显示了如何为各种属性提供值,包括以下内容:spring-doc.cadn.net.cn

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

入站通道适配器首先将文件检索到本地目录,然后根据 Poller 配置发出每个文件。 从版本 5.0 开始,当需要检索新文件时,您可以限制从 SFTP 服务器获取的文件数。 当目标文件很大或在具有持久文件列表过滤器的集群系统中运行时,这可能是有益的,本节稍后将讨论。 用max-fetch-size为此目的。 负值(默认值)表示没有限制,并且将检索所有匹配的文件。 有关更多信息,请参见入站通道适配器:控制远程文件获取。 从 5.0 版本开始,您还可以提供自定义的DirectoryScannerimplementation 添加到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

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

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

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

从版本 5.0 开始,SftpPersistentAcceptOnceFileListFilter使用内存中的SimpleMetadataStore默认应用于SftpInboundFileSynchronizer. 此过滤器也会与regexpattern选项,以及通过SftpInboundChannelAdapterSpec在 Java DSL 中。 您可以使用CompositeFileListFilter(或ChainFileListFilter).spring-doc.cadn.net.cn

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

此外,如果您配置filter要使用SftpPersistentAcceptOnceFileListFilter并且远程文件时间戳发生变化(导致它被重新获取),则默认的本地过滤器不允许处理这个新文件。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

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

SFTP 入站通道适配器是轮询使用者。 因此,你必须配置一个 Poller (全局默认值或本地元素)。 将文件传输到本地目录后,将显示一条带有java.io.File,因为其有效负载类型被生成并发送到由channel属性。spring-doc.cadn.net.cn

详细了解文件筛选和大文件

有时,刚刚出现在受监视 (远程) 目录中的文件并不完整。 通常,这样的文件是用一些临时扩展名(例如.writing在名为something.txt.writing),然后在写入过程完成后重命名。 在大多数情况下,开发人员只对完整的文件感兴趣,并且只想筛选这些文件。 要处理这些情况,您可以使用filename-pattern,filename-regexfilter属性。 如果您需要自定义过滤器实现,可以通过设置filter属性。 以下示例显示了如何执行此作:spring-doc.cadn.net.cn

<int-sftp:inbound-channel-adapter id="sftpInbondAdapter"
            channel="receiveChannel"
            session-factory="sftpSessionFactory"
            filter="customFilter"
            local-directory="file:/local-test-dir"
            remote-directory="/remote-test-dir">
        <int:poller fixed-rate="1000" max-messages-per-poll="10" task-executor="executor"/>
</int-sftp:inbound-channel-adapter>

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

从故障中恢复

您应该了解适配器的架构。 文件同步器获取文件,并且FileReadingMessageSource为每个同步文件发出一条消息。 如前所述,涉及两个过滤器。 这filter属性(和模式)引用远程 (SFTP) 文件列表,以避免获取已获取的文件。 这FileReadingMessageSource使用local-filter来确定哪些文件将作为消息发送。spring-doc.cadn.net.cn

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

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

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

<int-sftp:inbound-channel-adapter id="sftpAdapter"
        session-factory="sftpSessionFactory"
        channel="requestChannel"
        remote-directory-expression="'/sftpSource'"
        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-sftp: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

从版本 5.0 开始,入站通道适配器可以根据生成的本地文件名在本地构建子目录。 那也可以是远程子路径。 为了能够递归读取本地目录以根据层次结构支持进行修改,您现在可以提供内部FileReadingMessageSource替换为新的RecursiveDirectoryScanner基于Files.walk()算法。 看AbstractInboundFileSynchronizingMessageSource.setScanner()了解更多信息。 此外,您现在可以将AbstractInboundFileSynchronizingMessageSourceWatchService-基于DirectoryScanner通过使用setUseWatchService()选择。 它还为所有WatchEventType实例来对 local directory 中的任何修改做出反应。 前面显示的 reprocessing 示例基于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 SftpJavaApplication {

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

    @Bean
    public SessionFactory<SftpClient.DirEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost("localhost");
        factory.setPort(port);
        factory.setUser("foo");
        factory.setPassword("foo");
        factory.setAllowUnknownKeys(true);
        factory.setTestSession(true);
        return new CachingSessionFactory<>(factory);
    }

    @Bean
    public SftpInboundFileSynchronizer sftpInboundFileSynchronizer() {
        SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory());
        fileSynchronizer.setDeleteRemoteFiles(false);
        fileSynchronizer.setRemoteDirectory("foo");
        fileSynchronizer.setFilter(new SftpSimplePatternFileListFilter("*.xml"));
        return fileSynchronizer;
    }

    @Bean
    @InboundChannelAdapter(channel = "sftpChannel", poller = @Poller(fixedDelay = "5000"))
    public MessageSource<File> sftpMessageSource() {
        SftpInboundFileSynchronizingMessageSource source =
                new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer());
        source.setLocalDirectory(new File("sftp-inbound"));
        source.setAutoCreateLocalDirectory(true);
        source.setLocalFilter(new AcceptOnceFileListFilter<File>());
        source.setMaxFetchSize(1);
        return source;
    }

    @Bean
    @ServiceActivator(inputChannel = "sftpChannel")
    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 SftpJavaApplication {

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

    @Bean
    public IntegrationFlow sftpInboundFlow() {
        return IntegrationFlow
            .from(Sftp.inboundAdapter(this.sftpSessionFactory)
                    .preserveTimestamp(true)
                    .remoteDirectory("foo")
                    .regexFilter(".*\\.txt$")
                    .localFilenameExpression("#this.toUpperCase() + '.a'")
                    .localDirectory(new File("sftp-inbound")),
                 e -> e.id("sftpInboundAdapter")
                    .autoStartup(true)
                    .poller(Pollers.fixedDelay(5000)))
            .handle(m -> System.out.println(m.getPayload()))
            .get();
    }
}

处理不完整的数据

SftpSystemMarkerFilePresentFileListFilter用于筛选在远程系统上没有相应标记文件的远程文件。 有关配置信息,请参阅 Javadocspring-doc.cadn.net.cn

SFTP 流入站频道适配器

版本 4.3 引入了流入站通道适配器。 此适配器生成 payload 类型的 messageInputStream,允许您在不写入本地文件系统的情况下获取文件。 由于会话保持打开状态,因此使用应用程序负责在使用文件时关闭会话。 该会话在closeableResource标头 (IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE). 标准框架组件(例如FileSplitterStreamTransformer,则会自动关闭会话。 有关这些组件的更多信息,请参见File SplitterStream Transformer。 以下示例显示如何配置 SFTP 流入站通道适配器:spring-doc.cadn.net.cn

<int-sftp: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-sftp:inbound-streaming-channel-adapter>

您只能使用以下一项filename-pattern,filename-regex,filterfilter-expression.spring-doc.cadn.net.cn

从版本 5.0 开始,默认情况下,SftpStreamingMessageSource适配器通过使用SftpPersistentAcceptOnceFileListFilter基于 In-MemorySimpleMetadataStore. 默认情况下,此过滤器也与文件名模式(或 regex)一起应用。 如果需要允许重复项,可以使用AcceptAllFileListFilter. 您可以使用CompositeFileListFilter(或ChainFileListFilter). 后面显示的 Java 配置显示了一种在处理后删除远程文件以避免重复的技术。

有关SftpPersistentAcceptOnceFileListFilter及其使用方式,请参阅远程持久性文件列表过滤器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属性SftpStreamingMessageSourcefalse,标头包含一个SftpFileInfo对象。 您可以访问SftpClient.DirEntry对象SftpClient通过使用SftpFileInfo.getFileInfo()方法。 这fileInfoJson属性在使用 XML 配置时不可用,但您可以通过注入SftpStreamingMessageSource添加到您的配置类之一中。 另请参阅远程文件信息spring-doc.cadn.net.cn

使用 Java 配置进行配置

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

@SpringBootApplication
public class SftpJavaApplication {

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

    @Bean
    @InboundChannelAdapter(channel = "stream")
    public MessageSource<InputStream> ftpMessageSource() {
        SftpStreamingMessageSource messageSource = new SftpStreamingMessageSource(template());
        messageSource.setRemoteDirectory("sftpSource/");
        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 SftpRemoteFileTemplate template() {
        return new SftpRemoteFileTemplate(sftpSessionFactory());
    }

    @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可用;当配置为 Poller Advice 时,入站适配器可以轮询多个服务器和目录。 配置建议并将其正常添加到 Poller 的建议链中。 一个DelegatingSessionFactory用于选择服务器,有关更多信息,请参阅 Delegating Session Factory。 建议配置由一个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

可以使用fairconstructor arg 的 Constructor Arg 中:spring-doc.cadn.net.cn

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

在这种情况下,无论上一个 poll 是否返回文件,通知都将移动到下一个服务器/目录。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(Sftp.inboundAdapter(sf())
                    .filter(new SftpPersistentAcceptOnceFileListFilter(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在轮询器上有关更多信息,请参见Conditional Pollers for Message Sources

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

在配置入站通道适配器时,应考虑两个属性。max-messages-per-poll与所有 Poller 一样,可用于限制每次轮询时发出的消息数(如果已准备好超过配置的值)。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:适配器最多获取 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 或通过控制总线)有效地阻止适配器获取更多文件,但允许 Poller 继续为以前获取的文件发出消息。 如果在更改属性时 poller 处于活动状态,则更改将在下一次轮询时生效。spring-doc.cadn.net.cn

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

SFTP 出站通道适配器

SFTP 出站通道适配器是一种特殊的MessageHandler连接到远程目录,并为它作为传入Message. 它还支持文件的多种表示形式,因此您不仅限于File对象。 与 FTP 出站适配器类似,SFTP 出站通道适配器支持以下有效负载:spring-doc.cadn.net.cn

以下示例说明如何配置 SFTP 出站通道适配器:spring-doc.cadn.net.cn

<int-sftp:outbound-channel-adapter id="sftpOutboundAdapter"
    session-factory="sftpSessionFactory"
    channel="inputChannel"
    charset="UTF-8"
    remote-file-separator="/"
    remote-directory="foo/bar"
    remote-filename-generator-expression="payload.getName() + '-mysuffix'"
    filename-generator="fileNameGenerator"
    use-temporary-filename="true"
    chmod="600"
    mode="REPLACE"/>

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

SPEL 和 SFTP 出站适配器

与 Spring 集成中的许多其他组件一样,在配置 SFTP 出站通道适配器时,可以通过指定两个属性来使用 Spring 表达式语言 (SPEL):remote-directory-expressionremote-filename-generator-expression (前面描述的)。 表达式评估上下文将消息作为其根对象,这允许您使用表达式,这些表达式可以根据消息中的数据(来自“payload”或“headers”)动态计算文件名或现有目录路径。 在前面的示例中,我们定义了remote-filename-generator-expression属性,其表达式值根据文件名的原始名称计算文件名,同时还附加后缀:“-mysuffix”。spring-doc.cadn.net.cn

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

IGNOREFAIL,则不会传输文件。FAIL导致引发异常,而IGNORE以 Silent Json 的形式忽略传输(尽管DEBUGlog entry 生成)。spring-doc.cadn.net.cn

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

避免部分写入的文件

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

为了解决这个问题, Spring 集成 SFTP 适配器使用一种通用算法,其中文件以临时名称传输,并在完全传输后重命名。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 SftpJavaApplication {

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

    @Bean
    public SessionFactory<SftpClient.DirEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost("localhost");
        factory.setPort(port);
        factory.setUser("foo");
        factory.setPassword("foo");
        factory.setAllowUnknownKeys(true);
        factory.setTestSession(true);
        return new CachingSessionFactory<SftpClient.DirEntry>(factory);
    }

    @Bean
    @ServiceActivator(inputChannel = "toSftpChannel")
    public MessageHandler handler() {
        SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
        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 = "toSftpChannel")
         void sendToSftp(File file);

    }
}

使用 Java DSL 进行配置

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

@SpringBootApplication
public class SftpJavaApplication {

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

    @Bean
    public IntegrationFlow sftpOutboundFlow() {
        return IntegrationFlow.from("toSftpChannel")
            .handle(Sftp.outboundAdapter(this.sftpSessionFactory, FileExistsMode.FAIL)
                         .useTemporaryFileName(false)
                         .remoteDirectory("/foo")
            ).get();
    }

}

SFTP 出站网关

SFTP 出站网关提供了一组有限的命令,允许您与远程 SFTP 服务器进行交互:spring-doc.cadn.net.cn

使用ls命令

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

此外,文件名过滤的提供方式与inbound-channel-adapter.spring-doc.cadn.net.cn

lsoperation 是文件名列表或FileInfo对象(取决于您是否使用-1switch) 的 这些对象提供修改时间、权限等信息。spring-doc.cadn.net.cn

远程目录ls执行 action on 的命令在file_remoteDirectory页眉。spring-doc.cadn.net.cn

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

如果 remote path to list 以符号开头,则 SFTP 会将其视为绝对路径;without - 作为当前用户 home 中的相对路径。/spring-doc.cadn.net.cn

nlst命令

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

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

nlstoperation 是文件名列表。spring-doc.cadn.net.cn

file_remoteDirectoryheader 包含远程目录,其中nlst命令起作用。spring-doc.cadn.net.cn

SFTP 协议不提供列出名称的功能。 此命令相当于ls命令与-1选项,为方便起见,在此处添加。spring-doc.cadn.net.cn

使用get命令

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

file_remoteDirectoryheader 包含远程目录,而file_remoteFileheader 包含文件名。spring-doc.cadn.net.cn

get作是File对象。 如果您使用-stream选项,则 payload 是一个InputStream而不是File. 对于文本文件,一个常见的用例是将此作与文件拆分器流转换器结合使用。 将远程文件作为流使用时,您负责关闭Session在流被消费后。 为方便起见,SessioncloseableResourceheader 和IntegrationMessageHeaderAccessor提供便利的方法:spring-doc.cadn.net.cn

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

框架组件(如 File SplitterStream Transformer)在传输数据后自动关闭会话。spring-doc.cadn.net.cn

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

<int-sftp: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>object(即ListFile对象,每个对象代表一个检索到的文件)。spring-doc.cadn.net.cn

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

您使用的表达式 determine the remote path 应生成一个结果,例如,该*myfiles/*myfiles.spring-doc.cadn.net.cn

从版本 5.0 开始,您可以使用递归MGETFileExistsMode.REPLACE_IF_MODIFIED模式,以定期在本地同步整个远程目录树。 此模式将本地文件的上次修改时间戳设置为远程文件的时间戳,而不管-P(保留时间戳)选项。spring-doc.cadn.net.cn

使用递归时的注意事项 (-R)

该模式将被忽略并被假定。 默认情况下,将检索整个远程树。 但是,您可以通过提供*FileListFilter. 您还可以通过这种方式筛选树中的目录。 一个FileListFilter可以通过引用或filename-patternfilename-regex属性。 例如filename-regex="(subDir|.*1.txt)"检索所有以1.txt在远程目录和子目录中subDir. 但是,我们将在本说明之后介绍可用的替代方法。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 开始,您可以配置SftpSimplePatternFileListFilterSftpRegexPatternFileListFilter始终传递目录,方法是将alwaysAcceptDirectortiestrue. 这样做允许对简单模式进行递归,如下例所示:spring-doc.cadn.net.cn

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

<bean id="dotStarDotTxtFilter"
            class="org.springframework.integration.sftp.filters.SftpRegexPatternFileListFilter">
    <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(或 expression) 用于命名远程文件。 其他可用属性包括remote-directory,temporary-remote-directory及其*-expression等价物:use-temporary-file-nameauto-create-directory. 有关更多信息,请参阅 schema documentation.spring-doc.cadn.net.cn

put作是String,其中包含传输后服务器上文件的完整路径。spring-doc.cadn.net.cn

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

使用mput命令

mput将多个文件发送到服务器并支持以下选项: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>object(即List传输产生的远程文件路径)。spring-doc.cadn.net.cn

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

使用rm命令

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

如果 remove作成功,则生成的消息有效负载为Boolean.TRUE. 否则,消息负载为Boolean.FALSE. 这file_remoteDirectoryheader 包含远程目录,而file_remoteFileheader 保存文件名。spring-doc.cadn.net.cn

使用mv命令

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

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

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

其他命令信息

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

getmget命令支持local-directory-expression属性。 它定义了一个 SPEL 表达式,用于在传输期间生成本地目录的名称。 评估上下文的根对象是请求消息。 这remoteDirectory变量也可用。 它对 mget 特别有用(例如:local-directory-expression="'/tmp/local/' + #remoteDirectory.toUpperCase() + headers.myheader"). 此属性与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="-1",则有效负载将是一个FileInfo对象。 您可以将选项作为空格分隔的列表(例如command-options="-1 -dirs -links").spring-doc.cadn.net.cn

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

使用 Java 配置进行配置

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

@SpringBootApplication
public class SftpJavaApplication {

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

    @Bean
    @ServiceActivator(inputChannel = "sftpChannel")
    public MessageHandler handler() {
        return new SftpOutboundGateway(ftpSessionFactory(), "ls", "'my_remote_dir/'");
    }

}

使用 Java DSL 进行配置

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

@SpringBootApplication
public class SftpJavaApplication {

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

    @Bean
    public SessionFactory<SftpClient.DirEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory sf = new DefaultSftpSessionFactory();
        sf.setHost("localhost");
        sf.setPort(port);
        sf.setUsername("foo");
        sf.setPassword("foo");
        factory.setTestSession(true);
        return new CachingSessionFactory<>(sf);
    }

    @Bean
    public QueueChannelSpec remoteFileOutputChannel() {
        return MessageChannels.queue();
    }

    @Bean
    public IntegrationFlow sftpMGetFlow() {
        return IntegrationFlow.from("sftpMgetInputChannel")
            .handle(Sftp.outboundGateway(sftpSessionFactory(),
                            AbstractRemoteFileOutboundGateway.Command.MGET, "payload")
                    .options(AbstractRemoteFileOutboundGateway.Option.RECURSIVE)
                    .regexFileNameFilter("(subSftpSource|.*1.txt)")
                    .localDirectoryExpression("'myDir/' + #remoteDirectory")
                    .localFilenameExpression("#remoteFileName.replaceFirst('sftpSource', 'localTarget')"))
            .channel("remoteFileOutputChannel")
            .get();
    }

}

出站网关部分成功 (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由 gateway 抛出的derivedInputfile1.txt,subdirzoo.txtpartialResultsfile1.txt. 其cause是另一个PartialSuccessExceptionderivedInputfile2.txtfile3.txtpartialResultsfile2.txt.spring-doc.cadn.net.cn

MessageSessionCallback 回调

从 Spring 集成版本 4.2 开始,您可以使用MessageSessionCallback<F, T>implementation 替换为<int-sftp:outbound-gateway/> (SftpOutboundGateway) 对Session<SftpClient.DirEntry>使用requestMessage上下文。 您可以将其用于任何非标准或低级 SFTP作(或多个),例如允许从集成流定义或功能接口 (lambda) 实施注入进行访问。 以下示例使用 lambda:spring-doc.cadn.net.cn

@Bean
@ServiceActivator(inputChannel = "sftpChannel")
public MessageHandler sftpOutboundGateway(SessionFactory<SftpClient.DirEntry> sessionFactory) {
    return new SftpOutboundGateway(sessionFactory,
         (session, requestMessage) -> session.list(requestMessage.getPayload()));
}

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

使用 XML 配置时,<int-sftp:outbound-gateway/>提供session-callback属性,允许您指定MessageSessionCallbackBean 名称。spring-doc.cadn.net.cn

session-callbackcommandexpression属性。 使用 Java 进行配置时,SftpOutboundGatewayclass 提供不同的构造函数。

Apache Mina SFTP 服务器事件

ApacheMinaSftpEventListener,在版本 5.2 中添加,侦听某些 Apache Mina SFTP 服务器事件并将其发布为ApplicationEvents 可以被任何ApplicationListener@EventListenerbean 方法或 Event Inbound Channel Adapterspring-doc.cadn.net.cn

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

它们中的每一个都是ApacheMinaSftpEvent;您可以配置单个侦听器来接收所有事件类型。 这source属性是ServerSession,您可以从中获取客户端地址等信息;一个方便的getSession()method 在 abstract 事件上提供。spring-doc.cadn.net.cn

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

server = SshServer.setUpDefaultServer();
...
SftpSubsystemFactory sftpFactory = new SftpSubsystemFactory();
sftpFactory.addSftpEventListener(apacheMinaSftpEventListenerBean);
...

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

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

远程文件信息

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

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