Understanding Apache Camel Dynamic Routing

Go To StackoverFlow.com


I have set up a simple dynamic router:

    public String slip(String body, @Header(Exchange.SLIP_ENDPOINT) String previous) {
                if (previous == null) {
                    return "mock:a";
                    else if (body.contains("status=2") ) {
                    return "mock:b";
                    else if (body.contains("status=3") ) {
                    return "mock:c";

                // no more so return null
                return null;

Mock a,b,c are routes with custom processors.

public void process(Exchange exchange) throws Exception {
        String str_request = "";
        String str_requestNew = "";

        str_request = (String) exchange.getIn().getBody();

            str_requestNew = "status=2";
  1. How do I update the message body between routes in my custom processor via Java DSL. exchange.getOut().setBody(newreq); ?

  2. Do I need to create a new producer and send the message back to the dynamic router? ProducerTemplate template = exchange.getContext().createProducerTemplate(); template.sendBody(myDynamicRouterEndpoint, newreq); or will my router pick up the new body if do it via method 1.

Or is there a huge flaw in my logic all together? :)

2012-04-03 23:04
by esimran


You can do it like you describe in 1.

It is even simpler if you use the bean component. Then you can have a plain java method for reading and setting the body:

public String doSomething(String body) { }

This will get the body in the parameter and the return value will be the new body. This also makes your bean independent of Camel.

2012-04-04 05:35
by Christian Schneider
Ah ok. that's helpful thanks. Do I have to route back to the dynamic router via "to(routerEndpoint)" or will camel do that automatically as long as the body is updated - esimran 2012-04-04 17:49
Yes Camel keep calling the dynamic router, until your bean return null. Null is the signal to the dynamic route, that its done. If you have a copy of the Camel in Action book, then see chapter 8 where this pattern is covered, and we have a number of examples in the source code you can look at as well. And the documentation at Apache also have some coverage and examples: http://camel.apache.org/dynamic-route - Claus Ibsen 2012-04-05 10:10