自动路线发现Camel

时间:2015-07-09 13:04:25

标签: java xml spring apache-camel

在我的应用程序中,我有一些xml文件存储在一个声明我的路由的文件夹中。我想在应用程序引导程序中上传所有路由并将它们存储在我的驼峰上下文中。换句话说,我想自动发现存储在那些xml文件中的路由。

以下是包含路径

的文件示例
<?xml version="1.0" encoding="UTF-8"?>
<routeContext id="myRoute" xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="file:C:/LocalFTPServer" />
        <log message="Got a file!" loggingLevel="INFO" loggerRef="myLogger" />
        <choice>
            <when>
                <simple>${file:ext} == 'csv'</simple>
                <log message="I'm going to email you!" loggingLevel="INFO"
                    loggerRef="myLogger" />
            </when>
            <otherwise>
                <log message="File extension wrong." loggingLevel="WARN"
                    loggerRef="myLogger" />
            </otherwise>
        </choice>
    </route>
</routeContext>

这是我的应用程序上下文

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <import resource="beans/beans.xml" />

    <camelContext xmlns="http://camel.apache.org/schema/spring">
    </camelContext>

</beans>

1 个答案:

答案 0 :(得分:0)

如果您想在某些事件上添加路线,请使用context.addRouteDefinitions方法

例如:

    public class ContextStartEventListener extends EventNotifierSupport implements ApplicationContextAware {

        private ApplicationContext applicationContext;

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) {
            this.applicationContext = applicationContext;
        }

        @Override
        public void notify(EventObject event) throws Exception {
            if (event instanceof CamelContextStartedEvent) {
                try {
                    CamelContextStartedEvent startedEvent = (CamelContextStartedEvent) event;
                    DefaultCamelContext context=(DefaultCamelContext)startedEvent.getContext();
                    Resource[] xmlResources=applicationContext.getResources("classpath*:net/**/route.xml");
                    for (int i=0;i<xmlResources.length;i++) {
                        InputStream is = xmlResources[i].getInputStream();
                        RoutesDefinition routes = context.loadRoutesDefinition(is);
                        context.addRouteDefinitions(routes.getRoutes());
                    }       
                } catch (Throwable ex) {
                    // do something on error
                }
            }
        }
...
相关问题