37.3. 使用 Consumer Template
概述 复制链接链接已复制到粘贴板!
使用者模板提供了轮询消费者端点的方法,以接收传入的消息。您可以选择以交换对象的形式接收传入的消息,也可以采用消息正文格式(其中消息正文可以使用内置类型转换器来广播到特定类型的消息)。
轮询交换示例 复制链接链接已复制到粘贴板!
您可以使用以下轮询方法之一使用消费者模板来轮询消费者端点进行交换:块 receive(); 带有超时;或 receive() 接收NoWait(),该端点会立即返回。由于消费者端点代表服务,因此在尝试轮询交换之前,还要通过调用 start() 来启动服务线程。
以下示例演示了如何使用 blocking receive() 方法从 seda:foo 消费者端点轮询交换:
import org.apache.camel.ProducerTemplate;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Exchange;
...
ProducerTemplate template = context.createProducerTemplate();
ConsumerTemplate consumer = context.createConsumerTemplate();
// Start the consumer service
consumer.start();
...
template.sendBody("seda:foo", "Hello");
Exchange out = consumer.receive("seda:foo");
...
// Stop the consumer service
consumer.stop();
如果使用者模板实例 消费者,使用 CamelContext.createConsumerTemplate() 方法进行实例化,并通过调用 ConsumerTemplate.start() 启动使用者服务线程。
轮询消息正文示例 复制链接链接已复制到粘贴板!
您还可以使用以下方法之一为传入消息正文轮询使用者端点:blocking receiveBody(); receiveBody(), receiveBody(); 或 receiveBodyNoWait(),这将立即返回。如上例所示,在尝试轮询交换之前,还要通过调用 start() 来启动服务线程。
以下示例演示了如何使用块 receiveBody() 方法从 seda:foo 消费者端点轮询传入的邮件正文:
import org.apache.camel.ProducerTemplate;
import org.apache.camel.ConsumerTemplate;
...
ProducerTemplate template = context.createProducerTemplate();
ConsumerTemplate consumer = context.createConsumerTemplate();
// Start the consumer service
consumer.start();
...
template.sendBody("seda:foo", "Hello");
Object body = consumer.receiveBody("seda:foo");
...
// Stop the consumer service
consumer.stop();
轮询交换方法 复制链接链接已复制到粘贴板!
从消费者端点轮询 交换 有三种基本方法: receive() 无限,没有超时块; 接收(),指定毫秒的超时块; 接收NoWait() 是非阻塞的。您可以将使用者端点指定为端点 URI,也可以指定为 Endpoint 实例。
Exchange receive(String endpointUri);
Exchange receive(String endpointUri, long timeout);
Exchange receiveNoWait(String endpointUri);
Exchange receive(Endpoint endpoint);
Exchange receive(Endpoint endpoint, long timeout);
Exchange receiveNoWait(Endpoint endpoint);
轮询消息正文方法 复制链接链接已复制到粘贴板!
从消费者端点轮询 消息正文 有三种基本方法: receiveBody() 无限,没有超时块,receiveBody() 且具有指定毫秒的超时块; 接收BodyNoWait() 是非阻塞的。您可以将使用者端点指定为端点 URI,也可以指定为 Endpoint 实例。此外,通过调用这些方法的模板形式,您可以使用内置的类型转换器将返回的正文转换为特定类型的 T。
Object receiveBody(String endpointUri);
Object receiveBody(String endpointUri, long timeout);
Object receiveBodyNoWait(String endpointUri);
Object receiveBody(Endpoint endpoint);
Object receiveBody(Endpoint endpoint, long timeout);
Object receiveBodyNoWait(Endpoint endpoint);
<T> T receiveBody(String endpointUri, Class<T> type);
<T> T receiveBody(String endpointUri, long timeout, Class<T> type);
<T> T receiveBodyNoWait(String endpointUri, Class<T> type);
<T> T receiveBody(Endpoint endpoint, Class<T> type);
<T> T receiveBody(Endpoint endpoint, long timeout, Class<T> type);
<T> T receiveBodyNoWait(Endpoint endpoint, Class<T> type);