'Camel - How do we set a property using producer template?

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

  1. set the customer-id property on the exchange.
  2. use it later when required in the route

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.



Solution 1:[1]

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);

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 java-addict301
Solution 2