美文网首页
Spring boot项目集成Camel FTP

Spring boot项目集成Camel FTP

作者: KingOfLion | 来源:发表于2019-08-22 11:01 被阅读0次

    1、Spring 中集成camel-ftp

    近期项目中涉及到定期读取并解析ftp服务器上的文件,自己实现ftp-client有些复杂,而且还不知道要踩多少坑,因此考虑集成camel-ftp的方式来解决ftp文件的下载问题。自己则专注于文件的解析工作.

    附上demo地址: https://github.com/LuckyDL/java-demos

    1.1、POM引用

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-boot-starter</artifactId>
        <version>2.22.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-ftp</artifactId>
        <version>2.22.1</version>
    </dependency>
    
    
    • 注意:
      在选择版本的时候,如果SpringBoot版本是1.5.10.RELEASE的话,那么camel的版本最高只能使用2.21.2,使用2.22版本将会报错。经测试的配套关系如下:
    SrpingBoot Camel
    1.5 <=2.21.2
    2.0 >=2.22.x

    其他情况都会出现错误.

    1.2、SpringBoot application.yml配置

    ftp:
      addr: 172.18.18.19:21    # ftp地址、端口
      name: ftpuser
      password: ftp2018
      options: password=${ftp.password}&readLock=rename&delay=10s&binary=true&filter=#zipFileFilter&noop=true&recursive=true
      url: ftp://${ftp.name}@${ftp.addr}/?${ftp.options}
      # 本地下载目录
      local-dir: /var/data
    
    # 后台运行进程
    camel:
      springboot:
        main-run-controller: true
    
    management:
      endpoint:
        camelroutes:
          enabled: true
          read-only: true
    
    

    配置说明:

    • delay:每次读取时间间隔
    • filter: 指定文件过滤器
    • noop:读取后对源文件不做任何处理
    • recursive:递归扫描子目录,需要在过滤器中允许扫描子目录
    • readLock:对正在写入的文件的处理机制

    更多参数配置见官方手册

    1.3、配置路由

    要配置从远端服务器下载文件到本地,格式如下,from内部为我们在上面配置的url,to为本地文件路径。

    @Component
    public class DownloadRoute extends RouteBuilder {
        /** logger */
        private static final Logger logger = LoggerFactory.getLogger(DownloadRoute.class);
    
        @Value("${ftp.server.info}")
        private String sftpServer;
    
        @Value("${ftp.local.dir}")
        private String downloadLocation;
    
        @Autowired
        private DataProcessor dataProcessor;
    
        @Override
        public void configure() throws Exception{
            from(sftpServer)
                    .to(downloadLocation)
                    .process(dataProcessor)
                    .log(LoggingLevel.INFO, logger, "Download file ${file:name} complete.");
        }
    }
    
    

    说明:

    若将from配置为本地地址,to配置为远端地址,则可以实现向远端服务器上传文件

    process是数据处理器,如果仅仅是下载文件到本地,那么就不需要该配置。

    我们也可以配置多条路由也处理不同的业务,比如有多个ftp服务器需要连接的场景:

    @Override
        public void configure() throws Exception{
            // route1
            from(sftpServer)
                    .to(downloadLocation)
                    .process(dataProcessor)
                    .log(LoggingLevel.INFO, logger, "Download file ${file:name} complete.");
            // route2
            from(xxx).to(xxxx);
    
            // route3
            from(xxxx).to(xxx).process(xxx);
        }
    
    

    1.4、配置文件过滤

    如果ftp服务器上有很多文件,但是我们需要的只是其中的一种,由业务层来实现文件过滤肯定不合适,我们可以使用camel-ftp的文件过滤器,通过url中的filter来指定,如“filter=#zipFileFilter”, 用户需要实现GenericFileFilter接口的accept方法。
      例如我们只需要下载后缀名为.zip的压缩包到本地,过滤器的编写方法如下,因为我要递归扫描子目录,因此类型为目录的文件也需要允许通过。

    /**
     * camel ftp zip文件过滤器
     */
    @Component
    public class ZipFileFilter implements GenericFileFilter {
    
        @Override
        public boolean accept(GenericFile file) {
            return file.getFileName().endsWith(".zip") || file.isDirectory();
        }
    }
    
    

    1.5、文件处理器

    文件处理器就是我们对下载到本地的文件进行处理的操作,比如我们可能需要对下载的文件重新规划目录;或者解析文件并进行入库操作等。这就需要通过实现Processer的process方法。

    本文中的demo就是通过processor来解析zip包中的文件内容:

    @Component
    public class DataProcessor implements Processor {
    
        /** logger */
        private static final Logger logger = LoggerFactory.getLogger(DataProcessor.class);
    
        @Value("${ftp.local-dir}")
        private String fileDir;
    
        @Override
        public void process(Exchange exchange) throws Exception {
            GenericFileMessage<RandomAccessFile> inFileMessage = (GenericFileMessage<RandomAccessFile>) exchange.getIn();
            String fileName = inFileMessage.getGenericFile().getFileName();
            String file_path = fileDir + '/' + fileName;
            readZip(file_path);
        }
    
        ...   // 省略数据处理方法
    }
    
    

    2、参考资料

    关于camel ftp的各个参数配置,参见官方手册:http://camel.apache.org/ftp2.html

    此处需要注意的是,camel ftp手册里面只写了ftp独有的一些配置项,camel-ftp组件继承自camel-file,手册里面有说明,就一句话,稍不注意就可能忽略了,笔者就是没注意,被递归扫描子目录的问题折腾了2天(╥﹏╥ 阅读文档要细心,可能原作者字字珠玑)。。。因此有一些参数配置项可能在camel-ftp手册里面找不到,请移步至:http://camel.apache.org/file2.html

    相关文章

      网友评论

          本文标题:Spring boot项目集成Camel FTP

          本文链接:https://www.haomeiwen.com/subject/vzagsctx.html