Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

apache-camel

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.

like image 695
sat Avatar asked Dec 19 '22 13:12

sat


2 Answers

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);
like image 184
java-addict301 Avatar answered Feb 15 '23 09:02

java-addict301


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.

like image 44
Just a student Avatar answered Feb 15 '23 09:02

Just a student