Camel routing: sending each message to the right place

Routing decides where a message goes next, from a fixed choice between a few branches to a list of destinations computed at run time. This page explains the predicates Camel evaluates, then runs the content-based router, the message filter, the recipient list, the routing slip, the dynamic router and toD with Camel 4.23, including the missing end() and the static URI traps.

Contents

How Camel decides where a message goes

A route without routing sends every message along the same steps. Real flows branch: orders from Germany go to one warehouse, large orders need a manual check, notifications go to whichever channels the customer chose. Camel has several Enterprise Integration Patterns for this, and they differ in one question: is the set of destinations fixed in the route, or computed from the message at run time?

All of them rest on two building blocks:

  • Predicate: a test that returns true or false for an exchange. choice() and filter() evaluate predicates.
  • Expression: a value computed from an exchange, such as a header or a string built with the Simple language. recipientList(), routingSlip() and toD() evaluate an expression to get endpoint URIs.

Both are usually written in the Simple language, Camel's small expression language built into camel-core, but any language works: XPath for XML, JSONPath for JSON, a bean method, or a Java lambda.

Routing patterns in Camel
PatternDSLDestinationsBest for
Content-based routerchoice().when().otherwise()One of a fixed set of branchesIf/else on message content
Message filterfilter()One branch, or noneDropping or skipping messages
Recipient listrecipientList()Many, computed per message, called side by sideFan-out to a list chosen at run time
Routing sliproutingSlip()Many, computed once, called in sequenceA per-message pipeline
Dynamic routerdynamicRouter()One at a time, decided after each stepWorkflows where the next step depends on the last result
Dynamic totoD()One, computed per messageA single endpoint whose URI contains message data

The examples run with Camel 4.23 on Java 21, with camel-main and the core components on the classpath. The XPath example also needs camel-xpath and camel-xml-jaxp.

Content-based router: choice, when and otherwise

choice() is an if/else chain. The when clauses are tested in order, the first match wins, and otherwise catches the rest. Four orders exercise each branch, including one that matches two conditions:

Java
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class ChoiceRouter {

    static class OrderRoutes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:orders")
                .choice()
                    .when(header("country").isEqualTo("DE"))
                        .to("direct:eu-warehouse")
                    .when(simple("${body} > 1000"))
                        .to("direct:manual-review")
                    .otherwise()
                        .to("direct:us-warehouse")
                .end()
                .setBody(simple("routed ${body}"));

            from("direct:eu-warehouse").process(e -> print("EU warehouse ", e.getMessage()
                .getBody()));
            from("direct:manual-review").process(e -> print("manual review", e.getMessage()
                .getBody()));
            from("direct:us-warehouse").process(e -> print("US warehouse ", e.getMessage()
                .getBody()));
        }
    }

    static void print(String target, Object body) {
        System.out.println("  " + target + " <- " + body);
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new OrderRoutes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        Object[][] orders = {{"DE", 250}, {"US", 250}, {"US", 5000}, {"DE", 5000}};
        for (Object[] order : orders) {
            System.out.println("order " + order[1] + " from " + order[0]);
            Object reply = template.requestBodyAndHeader("direct:orders", order[1],
                "country", order[0]);
            System.out.println("  reply: " + reply);
        }
        camel.stop();
    }
}
Output
order 250 from DE
  EU warehouse  <- 250
  reply: routed 250
order 250 from US
  US warehouse  <- 250
  reply: routed 250
order 5000 from US
  manual review <- 5000
  reply: routed 5000
order 5000 from DE
  EU warehouse  <- 5000
  reply: routed 5000
  • Order 250 from DE matched the first when and went to the EU warehouse. Order 250 from US matched nothing and fell through to otherwise.
  • Order 5000 from US matched the second when, ${body} > 1000. The body arrived as an Integer, and Simple compared it with 1000 as a number.
  • Order 5000 from DE matched both conditions but went only to the EU warehouse. Only the first matching branch runs, so put the most specific test first; here a large German order skipped manual review, which is probably a bug in the order of the clauses.
  • Every reply starts with routed: after end(), the route continues with the next step whichever branch ran.

Without otherwise, a message that matches no when passes through the choice unchanged and carries on after end(). That is often what you want; if it is not, add an otherwise that logs or rejects the message.

Writing predicates

The same condition can be written in several ways. This program evaluates ten predicates against two messages without starting a route, which is also a quick way to try a Simple expression. The first message is a gift order marked urgent with priority high and amount 250; the second is a normal order with priority low and amount 30:

Java
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.builder.Builder;
import org.apache.camel.builder.PredicateBuilder;
import org.apache.camel.builder.ValueBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.DefaultExchange;

public class PredicateKinds {

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.start();
        ValueBuilder amount = Builder.header("amount");
        ValueBuilder priority = Builder.header("priority");

        Map<String, Predicate> predicates = new LinkedHashMap<>();
        predicates.put("simple: ${header.priority} == 'high'",
            simple(camel, "${header.priority} == 'high'"));
        predicates.put("simple: ${header.amount} > 100",
            simple(camel, "${header.amount} > 100"));
        predicates.put("simple: ${header.amount} range '1..50'",
            simple(camel, "${header.amount} range '1..50'"));
        predicates.put("simple: ${body} contains 'urgent'",
            simple(camel, "${body} contains 'urgent'"));
        predicates.put("simple: ${header.priority} in 'high,medium'",
            simple(camel, "${header.priority} in 'high,medium'"));
        predicates.put("simple: ${body} regex '.*[0-9]{4}.*'",
            simple(camel, "${body} regex '.*[0-9]{4}.*'"));
        predicates.put("header(amount).isGreaterThan(100)",
            amount.isGreaterThan(100));
        predicates.put("xpath: /order/@type = 'gift'",
            camel.resolveLanguage("xpath").createPredicate("/order/@type = 'gift'"));
        predicates.put("and(priority high, amount > 100)",
            PredicateBuilder.and(priority.isEqualTo("high"),
                amount.isGreaterThan(100)));
        predicates.put("Java lambda: body length > 20",
            exchange -> exchange.getMessage().getBody(String.class).length() > 20);

        Exchange[] messages = {
            message(camel, "<order type='gift'>urgent 2024</order>", "high", "250"),
            message(camel, "<order type='normal'>standard</order>", "low", "30"),
        };
        System.out.printf("%-46s %-7s %-7s%n", "predicate", "msg 1", "msg 2");
        for (Map.Entry<String, Predicate> entry : predicates.entrySet()) {
            Predicate predicate = entry.getValue();
            predicate.init(camel);
            System.out.printf("%-46s %-7s %-7s%n", entry.getKey(),
                predicate.matches(messages[0]), predicate.matches(messages[1]));
        }
        camel.stop();
    }

    static Predicate simple(CamelContext camel, String expression) {
        return camel.resolveLanguage("simple").createPredicate(expression);
    }

    static Exchange message(CamelContext camel, String body, String priority, String amount) {
        Exchange exchange = new DefaultExchange(camel);
        exchange.getMessage().setBody(body);
        exchange.getMessage().setHeader("priority", priority);
        exchange.getMessage().setHeader("amount", amount);
        return exchange;
    }
}
Output
predicate                                      msg 1   msg 2  
simple: ${header.priority} == 'high'           true    false  
simple: ${header.amount} > 100                 true    false  
simple: ${header.amount} range '1..50'         false   true   
simple: ${body} contains 'urgent'              true    false  
simple: ${header.priority} in 'high,medium'    true    false  
simple: ${body} regex '.*[0-9]{4}.*'           true    false  
header(amount).isGreaterThan(100)              true    false  
xpath: /order/@type = 'gift'                   true    false  
and(priority high, amount > 100)               true    false  
Java lambda: body length > 20                  true    true
  • The headers were set as the strings "250" and "30", yet > 100 and range '1..50' compared them as numbers. Compared as text, "30" would be greater than "100", and message 2 would have matched.
  • contains, in and regex are Simple operators too. Others include startsWith, endsWith, is for a type check, and !=; && and || combine conditions in one expression.
  • header("amount").isGreaterThan(100) is the typed builder form of the same test, and PredicateBuilder.and(...) combines builder predicates.
  • The XPath predicate read the type attribute from the XML body. It converted the String body to a DOM document first, which needs camel-xml-jaxp on the classpath; without it, the predicate fails with NoTypeConversionAvailableException.
  • The Java lambda matched both messages, since both bodies are longer than 20 characters. A lambda is a Predicate because the interface has one method, matches(Exchange).

Simple is the right default: it is short, it needs no extra jar, and it is parsed once when the route starts. Use a Java predicate or a bean method when the test needs real logic or a lookup, because a long Simple expression is hard to read and has no compiler to catch mistakes.

The missing end() trap

The Java DSL has no braces, so Camel needs end() to know where a choice() stops. Without it, every step after the last branch belongs to that branch. These two routes differ only in the end() before an audit step that should run for every customer:

Java
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class ChoiceEndTrap {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:withoutEnd")
                .choice()
                    .when(simple("${body} == 'gold'"))
                        .setHeader("discount", constant(20))
                    .otherwise()
                        .setHeader("discount", constant(0))
                .process(e -> System.out.println("  audit step ran for "
                    + e.getMessage().getBody()));

            from("direct:withEnd")
                .choice()
                    .when(simple("${body} == 'gold'"))
                        .setHeader("discount", constant(20))
                    .otherwise()
                        .setHeader("discount", constant(0))
                .end()
                .process(e -> System.out.println("  audit step ran for "
                    + e.getMessage().getBody()));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();
        for (String route : new String[] {"direct:withoutEnd", "direct:withEnd"}) {
            System.out.println(route);
            for (String tier : new String[] {"gold", "basic"}) {
                template.sendBody(route, tier);
            }
        }
        camel.stop();
    }
}
Output
direct:withoutEnd
  audit step ran for basic
direct:withEnd
  audit step ran for gold
  audit step ran for basic
  • Without end(), the audit step ran for basic only. It became part of the otherwise branch, so gold customers skipped it, and nothing in the build or the startup log says so.
  • With end(), the audit step ran for both, because it now follows the whole choice.

The same rule applies to filter(), split(), multicast() and every other EIP that holds child steps. When a when branch itself contains such an EIP, close it with endChoice() to return to the choice and add the next when; a plain end() there closes only the inner EIP. Indent the DSL like nested blocks, as in these examples, so a missing end() shows up when you read the code.

Message filter

filter() is a choice with a single branch: the steps inside it run only for matching messages. This program shows that messages which do not match still continue after end(), and how to drop them instead:

Java
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class FilterDemo {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:events")
                .filter(simple("${header.type} == 'payment'"))
                    .process(e -> System.out.println("  inside filter : "
                        + e.getMessage().getBody()))
                .end()
                .process(e -> System.out.println("  after filter  : "
                    + e.getMessage().getBody()));

            from("direct:stopEarly")
                .filter(simple("${header.type} != 'payment'"))
                    .stop()
                .end()
                .process(e -> System.out.println("  payment handled: "
                    + e.getMessage().getBody()));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        System.out.println("filter(...).end()");
        template.sendBodyAndHeader("direct:events", "pay #1", "type", "payment");
        template.sendBodyAndHeader("direct:events", "login #2", "type", "login");

        System.out.println("filter(...).stop() to drop messages");
        template.sendBodyAndHeader("direct:stopEarly", "pay #3", "type", "payment");
        template.sendBodyAndHeader("direct:stopEarly", "login #4", "type", "login");
        camel.stop();
    }
}
Output
filter(...).end()
  inside filter : pay #1
  after filter  : pay #1
  after filter  : login #2
filter(...).stop() to drop messages
  payment handled: pay #3
  • In the first route, only pay #1 ran the step inside the filter, but both messages reached the step after end(). The filter skips its own steps; it does not end the exchange.
  • In the second route, the filter matches what should be dropped and calls stop(), which ends the exchange there. login #4 never reached the payment step, and pay #3 did.

Use filter(...).stop(), or put the rest of the route inside the filter, when non-matching messages should go no further. A stopped exchange counts as completed, not failed, so the consumer treats the message as processed and does not redeliver it.

Recipient list: destinations from the message

A recipient list sends a copy of the message to every endpoint named by an expression. Here a header holds a comma-separated list of channels, and the third list names a fax: endpoint for which no component exists:

Java
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class RecipientListDemo {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:notify")
                .recipientList(header("channels")).ignoreInvalidEndpoints()
                .end()
                .process(e -> System.out.println("  back in caller route, body: "
                    + e.getMessage().getBody()));

            from("direct:email").process(e -> System.out.println("  email <- "
                + e.getMessage().getBody()));
            from("direct:sms").process(e -> System.out.println("  sms   <- "
                + e.getMessage().getBody()));
            from("direct:push").process(e -> System.out.println("  push  <- "
                + e.getMessage().getBody()));
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        String[] channelLists = {"direct:email,direct:sms", "direct:push",
            "direct:email,fax:office"};
        for (String channels : channelLists) {
            System.out.println("channels = " + channels);
            template.sendBodyAndHeader("direct:notify", "order shipped", "channels", channels);
        }
        camel.stop();
    }
}
Output
channels = direct:email,direct:sms
  email <- order shipped
  sms   <- order shipped
  back in caller route, body: order shipped
channels = direct:push
  push  <- order shipped
  back in caller route, body: order shipped
channels = direct:email,fax:office
  email <- order shipped
  back in caller route, body: order shipped
  • The first message went to email and then to SMS, in the order of the list, and the route then continued after end(). Each recipient received its own copy of the exchange.
  • The second message went only to push, since the list is evaluated for every message.
  • The third list reached email, and fax:office was skipped silently, because ignoreInvalidEndpoints() was set. Without it, the unknown scheme fails the exchange with ResolveEndpointFailedException.

The expression may return a delimited string, as here (the delimiter is a comma by default and can be changed with delimiter(";")), or a collection or array of URIs. Add parallelProcessing() to call the recipients at the same time on a thread pool, and an AggregationStrategy to combine their replies; by default the body that continues is the reply of the last recipient, which surprises people who expect the original message back. When the destinations are fixed in the route, multicast() does the same job, as the EIP patterns page shows.

Routing slip, dynamic router and toD

A recipient list calls each destination with a copy of the same message. A routing slip and a dynamic router instead form a pipeline, where each step receives the previous step's output. This program runs both, then compares toD() with a plain to() that contains the same Simple expression:

Java
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class DynamicRouting {

    public static String nextStep(Exchange exchange) {
        int done = exchange.getProperty("stepsDone", 0, Integer.class);
        exchange.setProperty("stepsDone", done + 1);
        String[] plan = exchange.getMessage().getHeader("plan", String.class).split(",");
        return done < plan.length ? "direct:" + plan[done] : null;
    }

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:slip")
                .routingSlip(header("steps"));

            from("direct:dynamic")
                .dynamicRouter(method(DynamicRouting.class, "nextStep"));

            from("direct:validate").setBody(simple("${body}+validated"));
            from("direct:price").setBody(simple("${body}+priced"));
            from("direct:ship").setBody(simple("${body}+shipped"));

            from("direct:static")
                .to("mock:${header.target}");
            from("direct:toD")
                .toD("direct:${header.target}");
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();

        System.out.println("routing slip : " + template.requestBodyAndHeader("direct:slip",
            "order", "steps", "direct:validate,direct:ship"));
        System.out.println("dynamic      : " + template.requestBodyAndHeader("direct:dynamic",
            "order", "plan", "validate,price,ship"));
        System.out.println("toD          : " + template.requestBodyAndHeader("direct:toD",
            "order", "target", "price"));
        System.out.println("to()         : " + template.requestBodyAndHeader("direct:static",
            "order", "target", "price"));
        System.out.println("endpoints    : " + camel.getEndpointRegistry().keySet().stream()
            .filter(k -> k.toString().contains("%7B") || k.toString().contains("price"))
            .toList());
        camel.stop();
    }
}
Output
routing slip : order+validated+shipped
dynamic      : order+validated+priced+shipped
toD          : order+priced
to()         : order
endpoints    : [direct://price, mock://$%7Bheader.target%7D]
  • The routing slip read direct:validate,direct:ship from the header once and ran the steps in order, so the body became order+validated+shipped.
  • The dynamic router called nextStep before every step. It returned direct:validate, then direct:price, then direct:ship, and finally null, which ends the routing. The bean keeps its position in an exchange property, because the router calls the same method again after each step.
  • toD("direct:${header.target}") evaluated the header and sent the message to direct:price, so the reply is order+priced.
  • to("mock:${header.target}") did not evaluate anything. It sent the message to an endpoint literally named ${header.target}, which appears in the endpoint registry as mock://$%7Bheader.target%7D, and the body came back unchanged. No error was raised, so the message simply went to the wrong place.

A dynamic router that never returns null loops forever, so make the end condition the first thing you write. With toD(), every distinct URI creates an endpoint and a producer that Camel caches; a URI that contains an order id creates one per order. Keep the changing values in headers instead, for example the CamelHttpPath header for an HTTP path, so that the URI stays the same and the endpoint is reused.

Choosing a routing pattern

Which routing pattern fits which need
NeedUse
Send each message to one of a few known placeschoice() with otherwise(), most specific test first
Skip some steps for some messagesfilter() around those steps
Drop messages that should not be processedfilter(...).stop()
Send copies to a fixed set of placesmulticast()
Send copies to a set chosen per messagerecipientList()
Run a sequence of steps listed in the messageroutingSlip()
Decide the next step after each stepdynamicRouter() with a clear null exit
One endpoint whose URI needs message datatoD(), keeping per-message values out of the URI where the component allows

Most routing bugs on this page are silent: a missing end(), a when that shadows a later one, a filter that does not stop, and a to() that sends to a literal ${...} name. Tests with mock endpoints catch all of them, as the Camel testing page shows. For the basics of routes and endpoints, start with the Camel introduction, and for processing parts of a message separately, see the splitter.