Search code examples
apache-camelmessaging

camel: use header value in multiple routes


Is it possible to set a header in one route and then use it again later in another route in the same context?
For example, I have a route that sets a header as so:

<setHeader headerName="clientId">
   <xpath>/Alarm/clientid/text()</xpath>
</setHeader>

The route uses Dead Letter Channel to send the message to an error route in the same context when delivery fails and I would like to use the clientId header I defined above in the message the error route sends, but currently calling the header returns nothing (an empty string I assume).


Solution

  • It should work , I am using camel 2.15.1 ,check the code below , if you run it you should see the header

    <bean id="mybean" class="java.lang.Exception" />
    <camel:camelContext xmlns="http://camel.apache.org/schema/spring"
        trace="false">
        <camel:errorHandler id="deadLetterErrorHandler"
            type="DeadLetterChannel" deadLetterUri="direct:b">
    
        </camel:errorHandler>
    
        <camel:route>
            <camel:from uri="timer:foo?repeatCount=1" />
            <camel:setHeader headerName="myheader">
                <camel:simple>Sundar</camel:simple>
            </camel:setHeader>
            <camel:to uri="direct:a" />
    
        </camel:route>
        <camel:route errorHandlerRef="deadLetterErrorHandler">
            <camel:from uri="direct:a" />
            <camel:throwException ref="mybean"></camel:throwException>
        </camel:route>
    
        <camel:route>
            <camel:from uri="direct:b" />
            <camel:log message="${in.header.myheader}"/>
        </camel:route>
    </camel:camelContext>
    

    It should print a log like below

    24 Feb 2016 19:09:47,707  route3 INFO  Sundar