camel的建立步骤

CamelContext是对Camel 运行时的一个抽象, 一般来说一个应用里面会有一个CamelContext 对象。一个典型的Camel 应用按照下面几个步骤执行。

   1. 创建一个CamelContext对象。
   2. 向CamelContext对象中添加Endpoints或者是Components
   3. 向CamelContext对象中添加路由(routes)规则
   4. 调用CamelContext的start() 方法,这样可以启动Camel内部有关消息发送,接收,处理所使用的线程。
   5. 当调用CamelContext的stop() 方法时,Camel 会将妥善关闭所有endpoint和Camel内部的线程。注意在调用CamelContext.start() 方法时并不一定阻塞, 而是在启动完每个Comonent和Endpoint的内部线程后start() 方法返回。而CamelContext.stop()方法会等待所有Endpoint和Component的内部线程都结束后 stop() 方法才返回。如果你没有在你的Camel 应用程序中调用CamelContext.start() 方法,那么由于内部线程并没有被创建那些消息将不会被处理。 如果你没有在你的Camel应用程序中调用CamelContext.stop()方法,那你你的应用将不会正常退出。如果你在一个JUnit 测试没有调用CamelContext.stop()方法,这可能会造成消息不能被完整地处理,而导致测试运行失败。


package com.chinacreator.mq;

import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.impl.DefaultCamelContext;

class JmsToFileRoute extends RouteBuilder {
    public void configure() {//路由规则,
        from("test-jms:TOOL.DEFAULT").to("file://test"); //test-jms为我们添加的组件名,此组件实际上是一个mq,TOOL.DEFAULT为一个队列名
        // set up a listener on the file component
        from("file://test").process(new Processor() { // 把发送到TOOL.DEFAULT的消息路由到test文件中            public void process(Exchange e) {
                System.out.println("Received exchange: " + e.getIn());
            }
        });
    }
}

public final class CamelJmsToFileExample {

    public static void main(String args[]) throws Exception {
        CamelContext context = new DefaultCamelContext();
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.11.104:61615");
        context.addComponent(" test-jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
       

        // Add routes to the CamelContext.
        context.addRoutes(new JmsToFileRoute());

        // Start the context.
        context.start();

        // End of main thread.
    }
}


public final class CamelJmsToFileExample {

    public static void main(String args[]) throws Exception {
        CamelContext context = new DefaultCamelContext();
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.11.104:61615");
        context.addComponent("test-jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
       

        // Add routes to the CamelContext.
        context.addRoutes(new JmsToFileRoute());

        // Start the context.
        context.start();

        // End of main thread.
    }
}


在运行之前我们需要启动一个mq服务器:tcp://192.168.11.104:61615,然后在运行这个程序,当我们向队列TOOL.DEFAULT发送消息时,我们就能受到文件消息,并且把消息保存在根目录下面

你可能感兴趣的:(apache,应用服务器,activemq,jms,Exchange)