What's the difference between "direct:" and to() in Apache Camel?

bacar picture bacar · Jun 8, 2012 · Viewed 11.9k times · Source

The DirectComponent documentation gives the following example:

from("activemq:queue:order.in")
    .to("bean:orderServer?method=validate")
    .to("direct:processOrder");

from("direct:processOrder")
    .to("bean:orderService?method=process")
    .to("activemq:queue:order.out");

Is there any difference between that and the following?

from("activemq:queue:order.in")
    .to("bean:orderServer?method=validate")
    .to("bean:orderService?method=process")
    .to("activemq:queue:order.out");

I've tried to find documentation on what the behaviour of the to() method is on the Java DSL, but beyond the RouteDefinition javadoc (which gives the very curt "Sends the exchange to the given endpoint") I've come up blank :(

Answer

Petter Nordlander picture Petter Nordlander · Jun 9, 2012

In the very case above, you will not notice much difference. The "direct" component is much like a method call.

Once you start build a bit more complex routes, you will want to segment them in several different parts for multiple reasons.

You can, for instance, create "sub routes" that could be reused among multiple routes in your Camel context. Much like you segment out methods in regular programming to allow reusability and make code more clear. The same goes for sub routes using, for instance the direct component.

The same approach can be extended. Say you want multiple protocols to be used as endpoints to your route. You can use the direct endpoint to create the main route, something like this:

// Three endpoints to one "main" route.
from("activemq:queue:order.in")
  .to("direct:processOrder");

from("file:some/file/path")
  .to("direct:processOrder");

from("jetty:http://0.0.0.0/order/in")
  .to("direct:processOrder");

from("direct:processOrder")
  .to("bean:orderService?method=process")
  .to("activemq:queue:order.out");

Another thing is that one route is created for each "from()" clause in DSL. A route is an artifact in Camel, and you could do certain administrative tasks towards it with the Camel API, such as start, stop, add, remove routes dynamically. The "to" clause is just an endpoint call.

Once starting to do some real cases with somewhat complexity in Camel, you will note that you cannot get too many "direct" routes.