camel系列-Direct和ProducerTemplate

Direct

当生产者发送消息交换时,Direct 组件提供对任何消费者的直接、同步调用。
此端点可用于连接同一Camel 上下文中的现有路由。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void testDirect() throws Exception {

CamelContext context=new DefaultCamelContext();

context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:home")
.process(exchange -> {
System.out.println("process:"+exchange.getIn().getBody());
});
}
});
context.start();
context.createProducerTemplate().sendBody("direct:home","hello");
Thread.sleep(2000);
}

ProducerTemplate

ProducerTemplate 接口允许您以各种不同的方式将消息交换发送到端点,从而可以轻松地从 Java 代码使用 Camel Endpoint 实例。

如果您只想向同一个端点发送大量消息,可以使用默认端点配置它;或者您可以指定 Endpoint 或 uri 作为第一个参数。

该 sendBody()方法允许您轻松地将任何对象发送到端点,如下所示:

发送消息

1
2
3
4
5
6
7
8
9
10
11
12
ProducerTemplate template = exchange.getContext().createProducerTemplate();

// send to default endpoint
template.sendBody("<hello>world!</hello>");

// send to a specific queue
template.sendBody("activemq:MyQueue", "<hello>world!</hello>");

// send with a body and header
template.sendBodyAndHeader("activemq:MyQueue",
"<hello>world!</hello>",
"CustomerRating", "Gold");

请求消息

ProducerTemplate 支持消息交换模式被用来控制消息风格来使用(MEP):

  • 发送方法-事件消息(InOnly)
  • 请求方法-请求回复(InOut)
1
2
3
4
5
6
7
Object response = template.requestBody("<hello/>");

// you can type convert the response to what you want such as String
String ret = template.requestBody("<hello/>", String.class);

// or specify the endpoint uri in the method
String ret = template.requestBody("cxf:bean:HelloWorldService", "<hello/>", String.class);