Apache-Camel-简单例子_第1页
Apache-Camel-简单例子_第2页
Apache-Camel-简单例子_第3页
Apache-Camel-简单例子_第4页
Apache-Camel-简单例子_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、一 demo工程1.下面给出一个从from到to有中间流程process处理的例子public class FileMoveWithCamel public static void main(String args) throws Exception CamelContext context = new DefaultCamelContext(); context.addRoutes(new RouteBuilder() /将d:/temp/inbox/下的文件经过process处理移到d:/temp/outbox public void configure() from("file

2、:d:/temp/inbox?noop=true").process(new FileConvertProcessor().to("file:d:/temp/outbox"); ); context.start(); boolean loop =true; while(loop) Thread.sleep(9000); context.stop(); class FileConvertProcessor implements Processor Override public void process(Exchange exchange) throws Excep

3、tion try InputStream body = exchange.getIn().getBody(InputStream.class); BufferedReader in = new BufferedReader(new InputStreamReader(body); StringBuffer strbf = new StringBuffer(""); String str = null; str = in.readLine(); while (str != null) System.out.println(str); strbf.append(str + &q

4、uot; "); str = in.readLine(); exchange.getOut().setHeader(Exchange.FILE_NAME, "converted.txt"); exchange.getOut().setBody(strbf.toString(); catch (IOException e) e.printStackTrace(); 推荐精选2.下面这个例子是每隔10秒访问一次http请求,并将访问到的内容写入文件 /* *1 Create a CamelContext. 2 Optionally, configure compone

5、nts or endpoints. 3 Add whatever routing rules you wish using the DSL and RouteBuilder or using Xml Configuration. 4 Start the context. */public class HttpPollWithQuartzCamel public static void main(String args) throws Exception CamelContext context = new DefaultCamelContext(); context.addRoutes(new

6、 RouteBuilder() public void configure() from("quartz:/report?cron=10 * * * * ?&stateful=true") .to("") .to("file:d:/temp/outbox?fileName=httpindex2.csv"); ); context.start(); boolean loop = true; while (loop) Thread.sleep(25000); context.stop(); 3. 在做系统集成的时候,必不可少的任务

7、就是将数据从一种格式转换为另一种格式,再把转换后的格式发到目标系统,在此用实例介绍一下Camel中利用Freemarker做数据转换.a :Freemarker的模板如下:<?xml version="1.0" encoding="UTF-8"?><people  xmlns:h="/TR/html4/">    <#escape x as x?xml>    <#list body.peop

8、leList as p>    <person id="000001" age="20">        <name>            <family>$p.fname</family>            <given&

9、gt;$p.gname</given>        </name>        <email>$p.email</email>        <link manager="$p.manager" />        <#if p.level = "L1&quo

10、t;>        <l1tag>xxx</l1tag>推荐精选        </#if>    </person>    </#list>    </#escape></people>b :与之对应的Java对象如下:每一个person节点对应一个ValueObject放在XMLTemplat

11、eParameter的peopleList里面.public class XMLTemplateParameter     private String fileName;        private List<ValueObject> peopleList = new ArrayList<ValueObject>();    public List<ValueObject> getPeopleList()    &#

12、160;    return peopleList;        public void setPeopleList(List<ValueObject> peopleList)         this.peopleList = peopleList;        public String getFileName()      &

13、#160;  return fileName;        public void setFileName(String fileName)         this.fileName = fileName;    public class ValueObject     private String fname;    private String gname; 

14、   private String email;    private String manager;    private String level;c :Route代码如下:public class CamelFreemarkerRoute extends RouteBuilder     public void configure() throws Exception         from("quartz:

15、/report?cron=10 * * * * ?&stateful=true")        .beanRef("fmBean","prepareFMValues")         .to("freemarker:com/test/camel/freemarker/test.ftl")        .to("fi

16、le:d:/temp/outbox?fileName=fm.xml");        推荐精选d :Route里用到的bean如下:xmlTemplateParameter做为顶级对象放在body里面,Freemarker里取数据的body.peopleList就对应于xmlTemplateParameter.peopleListpublic class FmProcessorBean         public void prepareFMValues(Exc

17、hange exchange)        XMLTemplateParameter xmlTemplateParameter = new XMLTemplateParameter();        ValueObject val = null;        for(int i=0;i<3;i+)           

18、0;val = new ValueObject();                    val.setFname("Yao");            val.setGname("Yorker" +i);            

19、;val.setEmail("test");            val.setManager("m&an<ager");            val.setLevel("L" + i);            xmlTemplateParameter

20、.getPeopleList().add(val);                                    exchange.getIn().setBody(xmlTemplateParameter);        e :Spring的配置文件如下:&

21、lt;beans xmlns="/schema/beans" xmlns:xsi="/2001/XMLSchema-instance" xmlns:camel="/schema/spring" xsi:schemaLocation="/schema/beans http:/www.springframewo

22、/schema/beans/spring-beans-3.0.xsd /schema/spring /schema/spring/camel-spring.xsd" default-autowire="byName" default-init-method="init">    <bean id="fmBean" class="com.test.camel

23、.freemarker.FmProcessorBean"/>    <camelContext id="testCamelContext" xmlns="/schema/spring">        <package>com.test.camel.freemarker</package>    </camelContext>&#

24、160;   </beans>f :启动Spring,在D:tempoutbox文件夹下,每隔10秒钟,会根据freemarker模板生成一个fm.xml文件.        ApplicationContext ac = new ClassPathXmlApplicationContext("config/camelFreemarker.xml");        while (true)    

25、60;        Thread.sleep(2000);        对本例beanRef("fmBean","prepareFMValues")的解释:推荐精选其意思是调用fmBean的prepareFMValues方法,Camel会负责将message的body绑定到要调用方法的第一个参数上面,其中可能做相应的类型转换.(本例中的方法的第一个参数为Exchange,没有转换的过程 ),这里给一个如下示例图解释这个绑定转换的过程

26、:Camel将Exchange的的input message(exchange.getIn()转换为String,绑定到mtd方法的name参数上.4下面是一个路由选择的例子 public class EIP /* * param * return * 方法描述 * author CaiWen * throws Exception * createTime 2014-11-19 * 接口名 */public static void main(String args) throws Exception ConnectionFactory conn = new ActiveMQConnection

27、Factory("vm:/localhost");CamelContext context = new DefaultCamelContext(); context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(conn); context.addRoutes(new RouteBuilder() public void configure() from("file:d:/temp/inbox?noop=true").to("jms:incoming

28、Orders"); from("jms:incomingOrders").choice().when(header("CamelFileName").endsWith(".xml") .to("jms:xmlOrders").when(header("CamelFileName").endsWith(".csv") .to("jms:csvOrders"); from("jms:csvOrders").process(new

29、Processor() Override public void process(Exchange arg0) throws Exception System.out.println("Recive xml order :"+arg0.getIn().getHeader("CamelFileName"); InputStream is = arg0.getIn().getBody(InputStream.class); BufferedReader br = new BufferedReader(new InputStreamReader(is); St

30、ring str = br.readLine(); while(str!=null) System.out.println(str); str = br.readLine(); ); from("jms:xmlOrders").process(new Processor() Override public void process(Exchange arg0) throws Exception 推荐精选 System.out.println("Recive xml order :" + arg0.getIn().getHeader("Camel

31、FileName"); ); ); context.start(); boolean loop =true; while(loop) Thread.sleep(9000); context.stop(); 5. 附加pom.xml <?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-inst

32、ance" xsi:schemaLocation="/POM/4.0.0 /maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.apache.camel</groupId><artifactId>examples</artifactId><version>2.14.0</vers

33、ion></parent><artifactId>camel-example-activemq-tomcat</artifactId><name>Camel : Example : ActiveMQ : Tomcat</name><description>An example using ActiveMQ Broker and Camel with Apache Tomcat</description><packaging>war</packaging><build>&

34、lt;plugins><plugin><groupId>org.codehaus.mojo</groupId><artifactId>tomcat-maven-plugin</artifactId><configuration><server>myTomcat</server><url>$tomcat.url</url><path>/$project.build.finalName</path></configuration><

35、/plugin><plugin><groupId>org.codehaus.mojo</groupId><artifactId>exec-maven-plugin</artifactId>推荐精选<configuration><mainClass>org.apache.camel.example.cxf.CamelRouteClient</mainClass><includePluginDependencies>false</includePluginDependencies

36、><systemProperties><property><key>java.util.logging.config.file</key><value>perties</value></property></systemProperties></configuration></plugin></plugins><!- Name of the generated WAR file -><finalName>came

37、l-example-activemq-tomcat</finalName></build><dependencies><!- camel -><dependency><groupId>org.apache.camel</groupId><artifactId>camel-core</artifactId></dependency><dependency><groupId>org.apache.camel</groupId><artif

38、actId>camel-spring</artifactId></dependency><dependency><groupId>org.apache.camel</groupId><artifactId>camel-stream</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifac

39、tId></dependency><!- camel jms and activemq -><dependency><groupId>org.apache.camel</groupId><artifactId>camel-jms</artifactId></dependency><dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-camel</arti

40、factId></dependency><dependency><groupId>org.apache.activemq</groupId>推荐精选<artifactId>activemq-broker</artifactId></dependency><dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-spring</artifactId></dep

41、endency><dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-kahadb-store</artifactId></dependency><dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-client</artifactId></dependency><d

42、ependency><groupId>org.apache.activemq</groupId><artifactId>activemq-pool</artifactId></dependency><!- xbean is required for ActiveMQ broker configuration in the spring xml file -><dependency><groupId>org.apache.xbean</groupId><artifactId&g

43、t;xbean-spring</artifactId></dependency><dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-quartz</artifactId></dependency><dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-http</artifactId>

44、;</dependency><dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-freemarker</artifactId></dependency><!- logging -><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId>推荐精选</dependency>&l

45、t;dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></dependency></dependencies><profiles><profile><id>Tomcat7</id><activation><activeByDefault>true</activeByDefault></activation><pro

46、perties><tomcat.url>http:/localhost:8080/manager/text</tomcat.url></properties></profile><profile><id>Tomcat6</id><properties><tomcat.url>http:/localhost:8080/manager</tomcat.url></properties></profile></profiles></p

47、roject>二应用场景及项目应用 Enterprise Application Integration 企业应用集成(EAI)企业应用集成是必要的,几乎每家公司都有很多新产品及应用,如何集成这些应用程序是一个问题。来每十年诞生一个新范式,例如客户端/服务器通信,面向服务的架构(SOA)或云计算。此外,不同的接口或协议和技术的出现。过去数据存储在文件,SQL数据库在今天很通用。有时,还需要NoSQL数据库。同步远程过程调用RPC或异步消息是通过如RMI,SOAP的Web服务,REST或JMS进行通信的。很多软件筒仓还存在。Enterprise Integration Patterns 企业集成模式(EIP)当然,你可以推倒重来,然后再写一些意大利面条代码,让应用程序协同工作。不幸的是,你的管理者不会喜欢这个缺少长远眼光的解决方案。企业集成模式()帮助碎片的问题,并使用标准化的方法来集成应用程序。使用相同的概念路由消息来改造。因此,每次有问题时重新发明轮子不是个好主意。推荐精选集成的替代方案解决方案1 :自定义解决方案实现一个单独的解决方案,适用于您的问题还没有分离切成碎片。此工程可能是最快的替代的小型用例。你必须自己编写所有。维护成本可能会高,特别是如果团队成员改变。解决方案2:集成框架使用这类

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论