Is there a way to set a camel exchange property using the producer template?
Imagine a rest endpoint that receives orders for a customer (not yet in the camel route). Using producer template, I would like to
Yes, I can also use headers and use producerTemplate.sendBodyWithHeaders when using the producer template, but I am thinking of using a property and not a header because thats what property is meant for - meta data inside a route vs headers is more meta data to communicate with external world. Customer-Id has no meaning outside a route for me.
To do this, you would set the property on your existing exchange and then pass it to one of the producerTemplate.send() overload methods that accept an Exchange parameter:
exchange.setProperty("propertyname", "propertyval");
producerTemplate.send("my-endpoint", exchange);
The answer by java-addict301 is helpful, but since it took me some time to figure out how to send an exchange with custom property and body, I figured I would share my solution:
producerTemplate.sendBodyAndProperty(myCustomBody, "customer-id", 42);
There are a couple of overrides available of the sendBodyAndProperty
method, a.o. to send to a specific endpoint(URI). And for even more customizability, you could also use:
producerTemplate.send("my-endpoint", exchange -> {
exchange.setProperty("customer-id", 42);
exchange.getIn().setBody(myCustomBody);
});
This is based on the implementation of sendBody
in Camel. Of course, this (i) removes the need to create your own Exchange
and (ii) makes it easy to do other custom actions with the exchange, if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With