Camel In Action 读书笔记 (3)

在第二章开始讲Camel的路由配置以及路由常用模式。

Camel的路由配置有三种方式:

1.java DSL (纯java方式)创建RouteBuilder

image

2.Spring DSL(纯spring方式)

image

3.定义bean的形式(Java+Spring)

image

路由常用模式

1.Using a content-based router(基于内容的路由)

image

如上图:路由到下一个节点时需要根据文件类型来判断是xmlOrders还是csvOrdersks可以通过choice…..when的形式来定义

headerCamel的表达式常用的有constant,simple,header,body.

from("jms:incomingOrders")      
.choice()                              
    .when(header("CamelFileName")
    .endsWith(".xml"))          
        .to("jms:xmlOrders")    
    .when(header("CamelFileName")
    .endsWith(".csv"))          
        .to("jms:csvOrders");
   

 

2.Using message filters(消息过滤)

image

如上图:如果消息(xml)order节点包含test属性则自动过滤掉。通过filter处理,如果是xml形式的消息可用xpath来解析消息


 
 
    /order[not(@test)]
   
 

3.Using multicasting(多点广播)

image

如上图,xmlOrders收到的消息要同时发送到accounting和production两个队列中去。通过multicast()来实现。

ExecutorService executor = Executors.newFixedThreadPool(16);
from("jms:xmlOrders")
   .multicast().parallelProcessing().executorService(executor)
    .to("jms:accounting", "jms:production");

注:可以不指定线程池,系统默认会创建一个线程池大小 为10:

from("jms:xmlOrders")
    .multicast().parallelProcessing()
    .to("jms:accounting", "jms:production");

4.Using recipient lists(收件人列表模式)

image

如上图,根据收件人列表来决定发送到哪些消息队列中去。

from("jms:xmlOrders")
.setHeader("customer", xpath("/order/@customer"))
.process(new Processor() {
    public void process(Exchange exchange) throws Exception {
        String recipients = "jms:accounting";
        String customer =
            exchange.getIn().getHeader("customer", String.class);
        if (customer.equals("honda")) {
            recipients += ",jms:production";
        }
        exchange.getIn().setHeader("recipients", recipients);
    }
})
.recipientList(header("recipients"));

recipientList也支持注解的形式:

from("jms:xmlOrders").bean(RecipientListBean.class);

public class RecipientListBean {
    @RecipientList
    public String[] route(@XPath("/order/@customer") String customer) {
        if (isGoldCustomer(customer)) {
            return new String[] {"jms:accounting", "jms:production"};
        } else {
            return new String[] {"jms:accounting"};
        }
    }

    private boolean isGoldCustomer(String customer) {
        return customer.equals("honda");
    }
}

6.Using the wireTap method(消息监听,复制)

image

如上图,在消息送到目的地的过程中对消息复制一份送到Tapdestination.

from("jms:incomingOrders")
.wireTap("jms:orderAudit")
.choice()
    .when(header("CamelFileName").endsWith(".xml"))
        .to("jms:xmlOrders")
    .when(header("CamelFileName").regex("^.*(csv|csl)$"))
        .to("jms:csvOrders")
    .otherwise()
        .to("jms:badOrders");

你可能感兴趣的:(Camel In Action 读书笔记 (3))