首页 > 解决方案 > 在 Spring Boot 应用程序中使用 Spring Integration 将文件下载到本地文件夹

问题描述

我是 Spring 集成框架的新手。目前我正在开发一个需要将文件下载到本地目录的项目。

我的目标是完成以下任务

1.通过调用spring集成将文件下载到本地目录

2.触发批处理作业。意思是读取文件并提取特定的列信息。

我能够连接到 SFTP 服务器。但是面临如何使用 spring 集成 java DSL 下载文件并触发批处理作业的困难。

下面的代码连接到 SFTP 会话工厂

@Bean
    public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost(sftpHost);
        factory.setPort(sftpPort);
        factory.setUser(sftpUser);

        if (sftpPrivateKey != null) {
            factory.setPrivateKey(sftpPrivateKey);
            factory.setPrivateKeyPassphrase(privateKeyPassPhrase);
        } else {
            factory.setPassword("sftpPassword");
        }

        factory.setPassword("sftpPassword");
        logger.info("Connecting to SFTP Server" + factory.getSession());
        System.out.println("Connecting to SFTP Server" + factory.getSession());
        factory.setAllowUnknownKeys(true);
        return new CachingSessionFactory<ChannelSftp.LsEntry>(factory);
    }

下面的代码将文件从远程下载到本地

@Bean
    public IntegrationFlowBuilder integrationFlow() {
        return IntegrationFlows.from(Sftp.inboundAdapter(sftpSessionFactory()));

    }

我正在使用弹簧集成 dsl。我无法在这里获得要编码的内容。

我正在尝试许多可能的方法来做到这一点。但无法得到如何继续这个要求。

谁能帮我解决这个问题,如果可能的话,请分享一个示例代码以供参考?

标签: spring-bootspring-integration

解决方案


Sftp.inboundAdapter()生成带有 aFile作为有效负载的消息。因此,IntegrationFlows.from(Sftp.inboundAdapter(sftpSessionFactory()))您可以将其视为完成的第一项任务。

从这里你的问题是你没有制作一个integrationFlow,而是返回它IntegrationFlowBuilder并将它注册为一个@Bean. 那就是它对你不起作用的地方。

您需要继续流定义并get()最终调用它以返回一个integrationFlow已经必须注册为 bean 的实例。如果此代码流有点混乱,请考虑将 an 实现IntegrationFlowAdapter@Component.

要触发批处理作业,您需要考虑在 EIP 方法中使用 a FileMessageToJobRequest.transform()然后JobLaunchingGateway.handle()EIP 方法中使用 a 。

在文档中查看更多信息:

https://docs.spring.io/spring-integration/reference/html/dsl.html#java-dsl https://docs.spring.io/spring-integration/reference/html/sftp.html#sftp-inbound https://docs.spring.io/spring-batch/docs/4.3.x/reference/html/spring-batch-integration.html#spring-batch-integration-configuration

顺便说一句,最后一个有一个完全适合您的用例的流程示例。


推荐阅读