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

georgeos:

我正在使用Spring Integration从SFTP服务器读取文件,并且使用带有Java配置的InboundChannelAdapter可以正常工作。

现在,我想修改我的过程,以便从SFTP服务器中删除所有已处理的文件。因此,我想将SFTP OutboundGateway与Java配置一起使用。这是我的新代码,基于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() + "]");
                }
            }

        };
    }

}

修改为:

  • 我将我的fileSynchronizer定义为setDeleteRemoteFiles(false),以便根据我的过程手动删除文件。
  • 在我的MessageHandler中,我添加了SFTPOutboundGateway,如果没有异常,则表示处理成功并删除了文件(但如果有异常,则不会删除文件)。

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

加里·罗素:
  1. 您不应该为每个请求创建一个新的网关(您正在执行的操作)。

  2. sftpOG无论如何,创建后您什么都不做您需要向网关发送消息。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章