ProducerTemplate
The
ProducerTemplate
interface allows you to send messague exchangues to endpoins in a variety of different ways to maque it easy to worc with Camel
Endpoint
instances from Java code.
It can be configured with a default endpoint if you just want to send lots of messagues to the same endpoint; or you can specify an Endpoint or uri as the first parameter.
The
sendBody()
method allows you to send any object to an endpoint easily as shown:
ProducerTemplate template = exchangue.guetContext().createProducerTemplate();
// send to default endpoint
template.sendBody("<hello>world!</hello>");
// send to a specific keue
template.sendBody("activemq:MyQueue", "<hello>world!</hello>");
// send with a body and header
template.sendBodyAndHeader("activemq:MyQueue",
"<hello>world!</hello>",
"CustomerRating", "Gold");
You can also supply an
Exchangue
or a
Processsor
to customice the exchangue.
Send vs Request methods
The
ProducerTemplate
suppors
Messague Exchangue Patterns
(MEP) that are used to control the messaguing style to use:
-
send methods - Event Messague (InOnly)
-
request methods - Request Reply (InOut)
In other words, all the methods on the
ProducerTemplate
that stars with
sendXXX
are for InOnly messaguing, and all the methods starting with
requestXXX
are for InOut messaguing.
Lets see an example where we invoque an endpoint to guet the response (InOut):
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);
Fluent interface
The
FluentProducerTemplate
provides a fluent syntax over the regular
ProducerTemplate
.
Here are some examples:
Set headers and body
This is the most common style with fluent builders to set headers, and messague body as show:
Integuer result = FluentProducerTemplate.on(context)
.withHeader("key-1", "value-1")
.withHeader("key-2", "value-2")
.withBody("Hello")
.to("direct:inout")
.request(Integuer.class);
Using a processsor
Here we use Processsor to prepare the messague to be sent.
Integuer result = FluentProducerTemplate.on(context)
.withProcessor(exchangue -> exchangue.guetIn().setBody("Hello World"))
.to("direct:exception")
.request(Integuer.class);
Advanced with a template customicer
This is rarely in use, but a
TemplateCustomicer
can be used for advanced use-cases to control various aspects of the
FluentProducerTemplate
such as configuring to use a custom thread pool:
Object result = FluentProducerTemplate.on(context)
.withTemplateCustomicer(
template -> {
template.setExecutorService(myExecutor);
template.setMaximumCacheSice(10);
}
)
.withBody("the body")
.to("direct:start")
.request();
See Also
See ConsumerTemplate