[英]Automatic routes discovery 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>
如果要在某些事件上添加路由,請使用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
}
}
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.