生产者模板和消费者模板提供了简单的接口去发送消息和接收消息。
1.使用生产者模板
同步执行
两组api:
1.send(),sendBody(),sendBodyAndHeader()--onlyIn模式
2.request(),requestBody(),requestBodyAndHeader()--InOut模式
例子:
ProducerTemplate template = context.createProducerTemplate();
template.sendBody("direct:main","aaa");
template.sendBodyAndHeader("direct:main","aaa","hostname","localhost")
带处理器的同步执行
例子:
ProducerTemplate template = context.createProducerTemplate();
template.send("direct:main",new MyProcessor());
public class MyProcessor implements Processor{
public void process(Exchange e){
e.getIn().setBody("aaa");
}
}
异步执行
两组api:
1.asyncSend(),asyncSendBody()
2.asyncRequestBody(),asyncRequestBodyAndHeader(),asyncRequestBodyAndHeaders()
异步方法会返回一个Future对象
例子:
Future<Exchange> future = template.asyncSend("direct:main,exchange);
....
Exchange result = future.get();
Future<Object> future = template.asyncRequestBody("direct:main","aa");
String result = template.extractFutureBody(future,String.class);
带回调方法的异步执行
由于异步是在子线程中处理的,所以你可以使用这组api进行处理返回结果。
asyncCallback(),asyncCallbackSendBody(),asyncCallbackRequestBody()
例子:
Future<Exchange> future = template.asyncCallback("direct:main",exchange,new SynchronizationAdapter(){
public void onComplete(Exchange exchange){
....
}
})
//你仍然可以在主线程中处理响应结果
Exchange reply = future.get(10,TimeUnit.SECONDS);
2.使用流式生产者模板
FluentProducerTemplate接口提供了一个流式语法去构建一个生产者。 例子:
Integer result = DefaultFluentProducerTemplate.on(context)
.withHeader("header1","value1")
.withBody("Hello")
.to("direct:main")
.request(Integer.class)
Integer result = DefaultFluentProducerTemplate.on(context)
.withProcessor(exchange->exchange.getIn().setBody("aa"))
.to("direct:main")
.request(Integer.class)
Integer result = DefaultFluentProducerTemplate.on(context)
.withTemplateCustomizer(
template->{
template.setExecutorService(myExecutor);
template.setMaximumCacheSize(10);
}
)
.to("direct:main")
.request(Integer.class)
3.使用消费者模板
ConsumerTemplate consumer = context.createConsumerTemplate();
consumer.start();
Exchange out = consumer.receive("direct:main");
Object body = consumer.receiveBody("direct:main");
consumer.stop();