Reusing routing logic by connecting routes
It is frequently necessary to execute the same processing steps within multiple routes. Camel provides you with a mechanism to call routing steps in a shared route. You can then reuse that route in a similar fashion to a method in a regular Java program.
This recipe will show you a strategy for developing your routes so that common routing tasks can be defined within a shared route called from other routes.
Getting ready
Determine the routing logic that you would like to reuse, and move it to a route that consumes from a direct:
URI.
The Java code for this recipe is located in the org.camelcookbook.structuringroutes.direct
package. The Spring XML files are located under src/main/resources/META-INF/spring
and prefixed with direct
.
How to do it...
Create a route with the from
URI using the direct:
endpoint, and then in another route, call the shared route using the same direct:
endpoint.
- The
direct:
endpoint name, which is an arbitrary alphanumeric string, follows the colon in the URI, must be unique within the containing Camel context:In the XML DSL, it is used as follows:
<route> <from uri="direct:prefixBodyWithHello"/> <transform> <simple>Hello, ${body}</simple> </transform> <log message="Prefixed message: ${body}"/> </route>
In the Java DSL, the same thing is expressed as:
from("direct:prefixBodyWithHello") .transform(simple("Hello, ${body}")) .log("Prefixed message: ${body}");
- Invoke the shared route from within the top-level route that needs to make use of this logic by using the same
direct:
URI:In the XML DSL, this is written as follows:
<route> <from uri="..."/> <to uri="direct:prefixBodyWithHello"/> </route>
In the Java DSL, this appears as:
from(...).to("direct:prefixBodyWithHello");
How it works...
Each direct:
endpoint may only be consumed (used within the from(...)
block) by one route in a Camel context. However, multiple routes may produce, or send, messages to that URI. This allows you to compose your routing logic in easily understandable blocks, much as you would when using methods in a regular Java program.
The shared route can be considered as a part of the top-level route. It operates on the same Exchange object, and participates in any transactions that the top-level route has initiated.
Regardless of whether the message exchange pattern on the exchange is InOnly
or InOut
, the behavior of invoking a direct:
endpoint is the same; that is, the exchange will flow through all of the processing steps defined in the shared route and will be returned to the calling route on completion where it will proceed to the next processing step.
There's more...
It is possible to invoke the shared route, and merge the returned exchange with the exchange containing the original state before the route was invoked. See the Enriching your content with some help from other endpoints recipe in Chapter 4, Transformation, for more details.
See also
- Direct Component: http://camel.apache.org/direct.html