如何使用Apache Camel SFTP拉取符合指定日期条件的文件
Apache Camel SFTP 按日期过滤拉取文件实现方案
方案1:使用SFTP组件内置filterFile属性(推荐)
Apache Camel 2.17及以上版本的SFTP组件原生支持filterFile配置项,可通过Simple表达式直接判断文件时间属性,无需额外编码:
- 先将你指定的固定日期转换为毫秒级时间戳,例如2024-01-01 00:00:00对应的时间戳为
1704067200000 - 在路由配置中直接添加过滤规则即可,Spring集成下Java DSL示例如下:
import org.apache.camel.builder.RouteBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SftpSyncRoute extends RouteBuilder { // 固定日期可从配置文件注入,也可以直接写常量 @Value("${custom.sftp.filter.timestamp:1704067200000}") private long targetTimestamp; @Override public void configure() throws Exception { from("sftp://your_username@sftp_host:22/remote_dir?password=your_password" + "&filterFile=${file.lastModified} > " + targetTimestamp) // 后续业务处理逻辑 .log("匹配到符合时间要求的文件:${file.name}") .to("bean:fileProcessService?method=handle"); } }
说明:如果需要按文件创建日期过滤,将
${file.lastModified}替换为${file.created}即可,部分SFTP服务器不支持返回创建时间时会自动回退为最后修改时间。
方案2:自定义过滤器实现复杂时间逻辑
如果需要处理时区转换、动态日期计算等复杂场景,可以自定义GenericFileFilter实现过滤:
- 自定义过滤器类:
import org.apache.camel.component.file.GenericFile; import org.apache.camel.component.file.GenericFileFilter; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class SftpDateFilter<T> implements GenericFileFilter<T> { private final LocalDateTime targetDate; public SftpDateFilter(LocalDateTime targetDate) { this.targetDate = targetDate; } @Override public boolean accept(GenericFile<T> file) { LocalDateTime fileTime = new Date(file.getLastModified()) .toInstant() .atZone(ZoneId.of("Asia/Shanghai")) // 统一时区避免偏差 .toLocalDateTime(); return fileTime.isAfter(targetDate); } }
- 在路由中注册并引用过滤器:
@Override public void configure() throws Exception { // 目标日期可从配置、数据库等位置读取 SftpDateFilter filter = new SftpDateFilter(LocalDateTime.of(2024, 1, 1, 0, 0)); getContext().getRegistry().bind("sftpDateFilter", filter); from("sftp://your_username@sftp_host:22/remote_dir?password=your_password&filter=#sftpDateFilter") .log("匹配到符合时间要求的文件:${file.name}") .to("bean:fileProcessService?method=handle"); }
注意事项
- 建议统一使用UTC时间戳做比较,避免SFTP服务器和本地服务时区不一致导致的判断错误
- 如果需要实现增量拉取(每次以上次拉取的最新文件时间为基准),可以配合Camel的
idempotentRepository存储上次拉取的最大时间戳动态更新过滤规则
内容的提问来源于stack exchange,提问作者prakash varma
相关产品推荐
相关产品推荐

