37.3. 使用使用者模板
概述
使用者模板提供了轮询消费者端点的方法,以接收传入的消息。您可以选择以交换对象的形式或消息正文的形式接收传入消息(其中消息正文可以使用内置类型转换器转换为特定类型)。
轮询交换示例
您可以使用使用者模板来轮询消费者端点以进行交换,使用以下轮询方法之一:blocking receive (); receive () with a timeout; 或 receiveNoWait () (会立即返回)。由于使用者端点表示服务,所以在尝试轮询轮询以进行交换之前,通过调用 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 () 来启动。
轮询消息正文示例
您还可以使用以下方法之一来轮询消费者端点:阻断 receiveBody (); receiveBody () (带有超时)或 receiveBodyNoWait (),这将立即返回。如上例中所示,在尝试轮询轮询以进行交换之前,还要通过调用 start () 启动服务线程。
以下示例演示了如何使用 blocking 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 () 无限期地没有超时块; receive () 为指定的时间毫秒;以及 receiveNoWait () 是非阻塞的。您可以将使用者端点指定为端点 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 () 无限超时块; 接收Body () 的指定期限为 毫秒;以及 receiveBodyNoWait () 是非阻塞的。您可以将使用者端点指定为端点 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);