camel-file 集成spring使用

来源:互联网 发布:2017淘宝网店数量 编辑:程序博客网 时间:2024/06/05 12:47
  • camel集成 spring需要导入camel-spring pom文件
<!-- 集成Spring --><dependency>    <groupId>org.apache.camel</groupId>    <artifactId>camel-spring</artifactId>    <version>${camel.version}</version></dependency>
  • camel-core中已经包含了camel-file组件了,所以不需要导入camel-file,只需要导入camel-core就行了
<dependency>    <groupId>org.apache.camel</groupId>    <artifactId>camel-core</artifactId>    <version>${camel.version}</version></dependency>
  • camel-file 集成 spring 配置文件内容如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">    <bean id="propertyConfigurer"        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="locations">            <list>                <!-- 这里支持多种寻址方式:classpath和file -->                <value>classpath:camel.properties</value>            </list>        </property>    </bean>    <bean id="fileFilter" class="com.xiaoka.camel.spring.file.CustomFileFilter" />    <!-- camel配置 -->    <camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">        <propertyPlaceholder id="camelProperties"            location="classpath:camel.properties" />        <route>            <from uri="file://{{file.path.from}}?noop=true&amp;scheduler=quartz2&amp;scheduler.cron=0/5 * * * * ?&amp;filter=#fileFilter&amp;runLoggingLevel=INFO" />            <log message="hello" />        </route>    </camelContext></beans>
  • 文件配置解释
{{file.path.from}}:配置文件中配置的需要读取的文件目录noop:表示不会对源文件进行任何修改操作scheduler:定时读取文件的定时器scheduler.cron:定时任务的cron表达式filter:对文件进行过滤,可根据文件名过滤,按照自己的需求来即可,下面会说明如何实现该类
  • 自定义file过滤器
    通过自定义过滤器可以灵活的筛选出符合要求的文件,需要实现接口org.apache.camel.component.file.GenericFileFilter 并实现其 accept 方法,如下:
package com.xiaoka.camel.spring.file;import java.text.SimpleDateFormat;import java.util.Date;import java.util.regex.Pattern;import org.apache.camel.component.file.GenericFile;import org.apache.camel.component.file.GenericFileFilter;public class CustomFileFilter implements GenericFileFilter {    //返回false 表示该文件将被筛选掉,不会读取    public boolean accept(GenericFile file) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");        System.out.println(file.getFileName() +" > "+(file.isDirectory()?"文件夹":"文件"));        if(file.getFileName().startsWith(sdf.format(new Date())+"-user")) {            return true;        }        return false;    }}
  • 在读取完文件后,可进行其他操作,这里仅仅打印了hello
原创粉丝点击