处理文件后通过 SftpOutboundGateway 删除文件

Remove file via SftpOutboundGateway after processing file

我正在使用 Spring 集成从 SFTP 服务器读取文件,使用具有 Java 配置的 InboundChannelAdapter 一切正常。

现在,我想修改我的流程,以便从 SFTP 服务器中删除所有已处理的文件。因此,我想使用具有 Java 配置的 SFTP OutboundGateway。这是我的新代码,基于 https://docs.spring.io/spring-integration/docs/5.0.0.BUILD-SNAPSHOT/reference/html/sftp.html#sftp-outbound-gateway:

进行了少量修改
@Configuration
public class SftpConfiguration {

    @Value("${sftp.host}")
    String sftpHost = "";

    @Value("${sftp.user}")
    String sftpUser = "";

    @Value("${sftp.pass}")
    String sftpPass = "";

    @Value("${sftp.port}")
    Integer sftpPort = 0;

    @Bean
    public SessionFactory<LsEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost(sftpHost);
        factory.setPort(sftpPort);
        factory.setUser(sftpUser);
        factory.setPassword(sftpPass);
        factory.setAllowUnknownKeys(true);
        return new CachingSessionFactory<LsEntry>(factory);
    }

    @Bean
    public SftpInboundFileSynchronizer sftpInboundFileSynchronizer() {
        SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory());
        fileSynchronizer.setDeleteRemoteFiles(false);
        fileSynchronizer.setRemoteDirectory("/upload/");
        return fileSynchronizer;
    }

    @Bean
    @InboundChannelAdapter(channel = "sftpChannel", poller = @Poller(cron = "0 * * * * ?"))
    public MessageSource<File> sftpMessageSource() {
        SftpInboundFileSynchronizingMessageSource source =
                new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer());
        source.setLocalDirectory(new File("sftp-folder"));
        source.setAutoCreateLocalDirectory(true);
        return source;
    }

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

            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                File f = (File) message.getPayload();
                try {
                    myProcessingClass.processFile(f);
                    SftpOutboundGateway sftpOG = new SftpOutboundGateway(sftpSessionFactory(), "rm",
                        "'/upload/" + f.getName() + "'");
                } catch(QuoCrmException e) {
                    logger.error("File [ Process with errors, file won't be deleted: " + e.getMessage() + "]");
                }
            }

        };
    }

}

修改为:

此代码未删除任何文件。有什么建议吗?

  1. 你不应该为每个请求创建一个新的网关(这是你正在做的)。

  2. 创建 sftpOG 之后,您没有对它做任何事情;您需要向网关发送消息。

您可以创建一个回复生成处理程序并将其输出通道连接到网关(应该是它自己的 @Bean)。

或者,您可以简单地使用 SftpRemoteFileTemplate 删除文件 - 但同样,您只需要一个,不需要为每个请求创建一个新文件。