Apache Camel 框架入門示例
Apache Camel是Apache基金會下的一個開源項目,它是一個基于規則路由和處理的引擎,提供企業集成模式的Java對象的實現,通過應用程序接口 或稱為陳述式的Java領域特定語言(DSL)來配置路由和處理的規則。其核心的思想就是從一個from源頭得到數據,通過processor處理,再發到一個to目的的.
這個from和to可以是我們在項目集成中經常碰到的類型:一個文件夾中的文件,一個MQ的queue,一個HTTP request/response,一個webservice等等.
Camel可以很容易集成到standalone的應用,在容器中運行的Web應用,以及和Spring一起集成.
下面用一個示例,介紹怎么開發一個最簡單的Camel應用.
1,從http://camel.apache.org/download.html下載Jar包.在本文寫作的時候最新版本是2.9. 本文用的是2.7,從2.7開始要求需要JRE1.6的環境.
下載的zip包含了Camel各種特性要用到的jar包.
在本文入門示例用到的Jar包只需要:camel-core-2.7.5.jar,commons-management-1.0.jar,slf4j-api-1.6.1.jar.
2,新建一個Eclipse工程,將上面列出的jar包設定到工程的Classpath.
新建一個如下的類:運行后完成的工作是將d:/temp/inbox/下的所有文件移到d:/temp/outbox
public class FileMoveWithCamel { public static void main(String args[]) throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(new RouteBuilder() { public void configure() { //from("file:d:/temp/inbox?noop=true").to("file:d:/temp/outbox"); from("file:d:/temp/inbox/?delay=30000").to("file:d:/temp/outbox"); } }); context.start(); boolean loop =true; while(loop){ Thread.sleep(25000); } context.stop(); } }
上面的例子體現了一個最簡單的路由功能,比如d:/temp/inbox/是某一個系統FTP到Camel所在的系統的一個接收目錄.
d:/temp/outbox為Camel要發送的另一個系統的接收目錄.
from/to可以是如下別的形式,讀者是否可以看出Camel是可以用于系統集成中做路由,流程控制一個非常好的框架了呢?
from("file:d:/temp/inbox/?delay=30000").to("jms:queue:order");
3,再給出一個從from到to有中間流程process處理的例子:
public class FileProcessWithCamel { public static void main(String args[]) throws Exception { CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {public void configure() { FileConvertProcessor processor = new FileConvertProcessor(); from("file:d:/temp/inbox?noop=true").process(processor).to("file:d:/temp/outbox"); } }); context.start(); boolean loop =true; while(loop){ Thread.sleep(25000); } context.stop(); }
}</pre>
這里的處理只是簡單的把接收到的文件多行轉成一行
public class FileConvertProcessor implements Processor{ @Override public void process(Exchange exchange) throws Exception { 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 + " "); str = in.readLine(); } exchange.getOut().setHeader(Exchange.FILE_NAME, "converted.txt"); // set the output to the file exchange.getOut().setBody(strbf.toString()); } catch (IOException e) { e.printStackTrace(); } } }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!