StreamingMessageSource продолжает срабатывать при применении фильтра - PullRequest
0 голосов
/ 10 января 2019

Я пытаюсь опросить каталог FTP для определенного типа файлов, опрос каталога работает, но всякий раз, когда я пытаюсь применить фильтр для фильтрации файлов по расширению, источник сообщений продолжает рассылать спам-сообщения о файле без относительно задержки опроса. Без фильтров все работает нормально, как только я включаю их, мое приложение аутентифицируется по FTP, загружает файл и отправляет сообщение без перерыва снова и снова. У меня есть следующие бобы:

/**
 * Factory that creates the remote connection
 *
 * @return DefaultSftpSessionFactory
 */
@Bean
public DefaultSftpSessionFactory sftpSessionFactory(@Value("${ftp.host}") String ftpHost,
                                                    @Value("${ftp.port}") int ftpPort,
                                                    @Value("${ftp.user}") String ftpUser,
                                                    @Value("${ftp.pass}") String ftpPass) {
    DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
    factory.setAllowUnknownKeys(true);
    factory.setHost(ftpHost);
    factory.setPort(ftpPort);
    factory.setUser(ftpUser);
    factory.setPassword(ftpPass);

    return factory;
}

/**
 * Template to handle remote files
 *
 * @param sessionFactory SessionFactory bean
 * @return SftpRemoteFileTemplate
 */
@Bean
public SftpRemoteFileTemplate fileTemplate(DefaultSftpSessionFactory sessionFactory) {
    SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sessionFactory);
    template.setAutoCreateDirectory(true);
    template.setUseTemporaryFileName(false);
    return template;
}

/**
 * To listen to multiple directories, declare multiples of this bean with the same inbound channel
 *
 * @param fileTemplate FileTemplate bean
 * @return MessageSource
 */
@Bean
@InboundChannelAdapter(channel = "deeplinkAutomated", poller = @Poller(fixedDelay = "6000", maxMessagesPerPoll = "-1"))
public MessageSource inboundChannelAdapter(SftpRemoteFileTemplate fileTemplate) {
    SftpStreamingMessageSource source = new SftpStreamingMessageSource(fileTemplate);
    source.setRemoteDirectory("/upload");
    source.setFilter(new CompositeFileListFilter<>(
            Arrays.asList(new AcceptOnceFileListFilter<>(), new SftpSimplePatternFileListFilter("*.trg"))
    ));

    return source;
}

/**
 * Listener that activates on new messages on the specified input channel
 *
 * @return MessageHandler
 */
@Bean
@ServiceActivator(inputChannel = "deeplinkAutomated")
public MessageHandler handler(JobLauncher jobLauncher, Job deeplinkBatch) {
    return message -> {
        Gson gson = new Gson();
        SFTPFileInfo info = gson.fromJson((String) message.getHeaders().get("file_remoteFileInfo"), SFTPFileInfo.class);
        System.out.println("File to download: " + info.getFilename().replace(".trg", ".xml"));
    };
}

1 Ответ

0 голосов
/ 11 января 2019

Я думаю AcceptOnceFileListFilter не подходит для файлов SFTP. Возвращенный LsEntry не соответствует ранее сохраненному в HashSet: только их хэши отличаются!

Попробуйте вместо этого использовать SftpPersistentAcceptOnceFileListFilter.

Также было бы лучше настроить DefaultSftpSessionFactory для isSharedSession:

/**
 * @param isSharedSession true if the session is to be shared.
 */
public DefaultSftpSessionFactory(boolean isSharedSession) {

Чтобы избежать повторного сеанса при каждом задании опроса.

у вас нет 6 секунд задержки между вызовами, потому что у вас есть maxMessagesPerPoll = "-1". Это означает опрос удаленных файлов, пока они не будут в удаленном каталоге. В вашем случае с AcceptOnceFileListFilter вы всегда получаете один и тот же файл по хэш-причине.

...