這個from和to可以是我們在項目集成中經常碰到的類型:一個FTP文件夾中的文件,一個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/outbox爲Camel要發送的另一個系統的接收目錄.
from/to可以是如下別的形式,讀者是否可以看出Camel是可以用於系統集成中做路由,流程控制一個非常好的框架了呢?
from("file:d:/temp/inbox/?delay=30000").to("jms:queue:order");//delay=30000是每隔30秒輪詢一次文件夾中是否有文件.
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();
- }
- }
- 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();
- }
- }
- }
- log4j.appender.stdout = org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.Target = System.out
- log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern = %-5p %d [%t] %c: %m%n
- log4j.rootLogger = debug,stdout