Apache Camel 简单例子.docx
- 文档编号:14325179
- 上传时间:2023-06-22
- 格式:DOCX
- 页数:16
- 大小:30.60KB
Apache Camel 简单例子.docx
《Apache Camel 简单例子.docx》由会员分享,可在线阅读,更多相关《Apache Camel 简单例子.docx(16页珍藏版)》请在冰点文库上搜索。
ApacheCamel简单例子
一demo工程
1.下面给出一个从from到to有中间流程process处理的例子
publicclassFileMoveWithCamel{
publicstaticvoidmain(String[]args)throwsException{
CamelContextcontext=newDefaultCamelContext();
context.addRoutes(newRouteBuilder(){
//将d:
/temp/inbox/下的文件经过process处理移到d:
/temp/outbox
publicvoidconfigure(){
from("file:
d:
/temp/inbox?
noop=true").process(newFileConvertProcessor()).to("file:
d:
/temp/outbox");
}
});
context.start();
booleanloop=true;
while(loop){
Thread.sleep(9000);
}
context.stop();
}
}
classFileConvertProcessorimplementsProcessor{
@Override
publicvoidprocess(Exchangeexchange)throwsException{
try{
InputStreambody=exchange.getIn().getBody(InputStream.class);
BufferedReaderin=newBufferedReader(newInputStreamReader(body));
StringBufferstrbf=newStringBuffer("");
Stringstr=null;
str=in.readLine();
while(str!
=null){
System.out.println(str);
strbf.append(str+"");
str=in.readLine();
}
exchange.getOut().setHeader(Exchange.FILE_NAME,"converted.txt");
exchange.getOut().setBody(strbf.toString());
}catch(IOExceptione){
e.printStackTrace();
}
}
}
2.下面这个例子是每隔10秒访问一次http请求,并将访问到的内容写入文件
/**
*1CreateaCamelContext.
2Optionally,configurecomponentsorendpoints.
3AddwhateverroutingrulesyouwishusingtheDSLandRouteBuilderorusingXmlConfiguration.
4Startthecontext.
*/
publicclassHttpPollWithQuartzCamel{
publicstaticvoidmain(Stringargs[])throwsException{
CamelContextcontext=newDefaultCamelContext();
context.addRoutes(newRouteBuilder(){
publicvoidconfigure(){
from("quartz:
//report?
cron=10****?
&stateful=true")
.to("")
.to("file:
d:
/temp/outbox?
fileName=httpindex2.csv");
}
});
context.start();
booleanloop=true;
while(loop){
Thread.sleep(25000);
}
context.stop();
}
}
3.在做系统集成的时候,必不可少的任务就是将数据从一种格式转换为另一种格式,再把转换后的格式发到目标系统,在此用实例介绍一下Camel中利用Freemarker做数据转换.
a:
Freemarker的模板如下:
xmlversion="1.0"encoding="UTF-8"?
>
h="http: //www.w3.org/TR/html4/"> <#escapexasx? xml> <#listbody.peopleListasp> <#ifp.level=="L1"> #if> #list> #escape>
b:
与之对应的Java对象如下:
每一个person节点对应一个ValueObject放在XMLTemplateParameter的peopleList里面.
publicclassXMLTemplateParameter{
privateStringfileName;
privateList
publicList
returnpeopleList;
}
publicvoidsetPeopleList(List
this.peopleList=peopleList;
}
publicStringgetFileName(){
returnfileName;
}
publicvoidsetFileName(StringfileName){
this.fileName=fileName;
}
}
publicclassValueObject{
privateStringfname;
privateStringgname;
privateStringemail;
privateStringmanager;
privateStringlevel;
c:
Route代码如下:
publicclassCamelFreemarkerRouteextendsRouteBuilder{
publicvoidconfigure()throwsException{
from("quartz:
//report?
cron=10****?
&stateful=true")
.beanRef("fmBean","prepareFMValues")
.to("freemarker:
com/test/camel/freemarker/test.ftl")
.to("file:
d:
/temp/outbox?
fileName=fm.xml");
}
}
d:
Route里用到的bean如下:
xmlTemplateParameter做为顶级对象放在body里面,Freemarker里取数据的body.peopleList就对应于xmlTemplateParameter.peopleList
publicclassFmProcessorBean{
publicvoidprepareFMValues(Exchangeexchange){
XMLTemplateParameterxmlTemplateParameter=newXMLTemplateParameter();
ValueObjectval=null;
for(inti=0;i<3;i++){
val=newValueObject();
val.setFname("Yao");
val.setGname("Yorker"+i);
val.setEmail("test@");
val.setManager("m&an val.setLevel("L"+i); xmlTemplateParameter.getPeopleList().add(val); } exchange.getIn().setBody(xmlTemplateParameter); } } e: Spring的配置文件如下: //www.springframework.org/schema/beans" xmlns: xsi="http: //www.w3.org/2001/XMLSchema-instance" xmlns: camel="http: //camel.apache.org/schema/spring" xsi: schemaLocation="http: //www.springframework.org/schema/beanshttp: //www.springframework.org/schema/beans/spring-beans-3.0.xsd http: //camel.apache.org/schema/springhttp: //camel.apache.org/schema/spring/camel-spring.xsd" default-autowire="byName"default-init-method="init"> //camel.apache.org/schema/spring"> f: 启动Spring,在D: tempoutbox文件夹下,每隔10秒钟,会根据freemarker模板生成一个fm.xml文件. ApplicationContextac=newClassPathXmlApplicationContext("config/camelFreemarker.xml"); while(true){ Thread.sleep(2000); } 对本例beanRef("fmBean","prepareFMValues")的解释: 其意思是调用fmBean的prepareFMValues方法,Camel会负责将message的body绑定到要调用方法的第一个参数上面,其中可能做相应的类型转换.(本例中的方法的第一个参数为Exchange,没有转换的过程),这里给一个如下示例图解释这个绑定转换的过程: Camel将Exchange的的inputmessage(exchange.getIn())转换为String,绑定到mtd方法的name参数上. 4.下面是一个路由选择的例子 publicclassEIP{ /** *@param *@return *@方法描述 *@authorCaiWen *@throwsException *@createTime2014-11-19 *@接口名 */ publicstaticvoidmain(String[]args)throwsException{ ConnectionFactoryconn=newActiveMQConnectionFactory("vm: //localhost"); CamelContextcontext=newDefaultCamelContext(); context.addComponent("jms",JmsComponent.jmsComponentAutoAcknowledge(conn)); context.addRoutes(newRouteBuilder(){ publicvoidconfigure(){ from("file: d: /temp/inbox? noop=true").to("jms: incomingOrders"); from("jms: incomingOrders").choice().when(header("CamelFileName").endsWith(".xml")) .to("jms: xmlOrders").when(header("CamelFileName").endsWith(".csv")) .to("jms: csvOrders"); from("jms: csvOrders").process(newProcessor(){ @Override publicvoidprocess(Exchangearg0)throwsException{ System.out.println("Recivexmlorder: "+arg0.getIn().getHeader("CamelFileName")); InputStreamis=arg0.getIn().getBody(InputStream.class); BufferedReaderbr=newBufferedReader(newInputStreamReader(is)); Stringstr=br.readLine(); while(str! =null){ System.out.println(str); str=br.readLine(); } } }); from("jms: xmlOrders").process(newProcessor(){ @Override publicvoidprocess(Exchangearg0)throwsException{ System.out.println("Recivexmlorder: "+arg0.getIn().getHeader("CamelFileName")); } }); } }); context.start(); booleanloop=true; while(loop){ Thread.sleep(9000); } context.stop(); } } 5.附加pom.xml xmlversion="1.0"encoding="UTF-8"? > //maven.apache.org/POM/4.0.0"xmlns: xsi="http: //www.w3.org/2001/XMLSchema-instance"xsi: schemaLocation="http: //maven.apache.org/POM/4.0.0http: //maven.apache.org/maven-v4_0_0.xsd"> : Example: : ActiveMQ: : Tomcat --NameofthegeneratedWARfile--> --camel--> --cameljmsandactivemq-->
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Apache Camel 简单例子 简单 例子