如何在SFTP轮询未检测到文件时添加日志记录
SFTP轮询无文件时添加日志记录的实现方案
方案一:使用轮询通知(Poller Advice)处理无消息场景
通过Spring Integration的ExpressionEvaluatingRequestHandlerAdvice,可以在轮询未获取到目标文件(即MessageSource返回null)时执行日志记录逻辑,无需自定义类,实现简洁。
步骤1:定义通知Bean
在SftpConfiguration类中添加以下Bean:
@Bean public ExpressionEvaluatingRequestHandlerAdvice noFileAdvice() { ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice(); // 无文件时执行的日志记录表达式 advice.setNoReplyExpressionString("T(org.slf4j.LoggerFactory).getLogger(T(com.yourpackage.SftpConfiguration)).info('SFTP轮询未检测到符合条件的*.txt文件')"); advice.setTrapException(false); return advice; }
步骤2:修改轮询器配置
更新@InboundChannelAdapter的@Poller注解,引用上述通知:
@Bean(name="sftpMessageSource") @InboundChannelAdapter(channel="fileuploaded", poller = @Poller(fixedDelay = "5000", advice = "noFileAdvice")) public MessageSource<File> sftpMessageSource(){ SftpInboundFileSynchronizingMessageSource source = new SftpInboundFileSynchronizingMessageSource(synchronizer()); source.setLocalDirectory(new File("tmp/incoming")); source.setAutoCreateLocalDirectory(true); source.setMaxFetchSize(1); return source; }
方案二:自定义MessageSource子类
如果需要更灵活的逻辑(比如根据远程目录状态输出不同日志),可以自定义SftpInboundFileSynchronizingMessageSource的子类,重写receive()方法:
步骤1:自定义MessageSource类
public class LoggingSftpMessageSource extends SftpInboundFileSynchronizingMessageSource { private static final Logger log = LoggerFactory.getLogger(LoggingSftpMessageSource.class); public LoggingSftpMessageSource(SftpInboundFileSynchronizer synchronizer) { super(synchronizer); } @Override public Message<File> receive() { Message<File> message = super.receive(); if (message == null) { log.info("SFTP轮询未检测到符合条件的*.txt文件"); } return message; } }
步骤2:替换原有MessageSource Bean
修改sftpMessageSource()方法,使用自定义类:
@Bean(name="sftpMessageSource") @InboundChannelAdapter(channel="fileuploaded", poller = @Poller(fixedDelay = "5000")) public MessageSource<File> sftpMessageSource(){ LoggingSftpMessageSource source = new LoggingSftpMessageSource(synchronizer()); source.setLocalDirectory(new File("tmp/incoming")); source.setAutoCreateLocalDirectory(true); source.setMaxFetchSize(1); return source; }
注意事项
- 确保项目已引入SLF4J相关依赖(Spring Boot默认包含),且日志配置正常输出。
- 方案一适合简单日志场景,方案二更适合需要扩展逻辑的场景。
内容的提问来源于stack exchange,提问作者Ishant
相关产品推荐
相关产品推荐

