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.
andchoice() evaluate predicates.filter() - Expression: a value computed from an exchange, such as a header or a string built with the Simple language.
,recipientList() androutingSlip() evaluate an expression to get endpoint URIs.toD()
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.
| Pattern | DSL | Destinations | Best for |
|---|---|---|---|
| Content-based router | choice().when().otherwise() | One of a fixed set of branches | If/else on message content |
| Message filter | filter() | One branch, or none | Dropping or skipping messages |
| Recipient list | recipientList() | Many, computed per message, called side by side | Fan-out to a list chosen at run time |
| Routing slip | routingSlip() | Many, computed once, called in sequence | A per-message pipeline |
| Dynamic router | dynamicRouter() | One at a time, decided after each step | Workflows where the next step depends on the last result |
| Dynamic to | toD() | One, computed per message | A 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()whenotherwise
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();
}
}
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
and went to the EU warehouse. Order 250 from US matched nothing and fell through towhen .otherwise - Order 5000 from US matched the second
,when . The body arrived as an${body} > 1000 , and Simple compared it with 1000 as a number.Integer - 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
: afterrouted , the route continues with the next step whichever branch ran.end()
Without otherwisewhenend()otherwise
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:
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;
}
}
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
and"250" , yet"30" and> 100 compared them as numbers. Compared as text,range '1..50' would be greater than"30" , and message 2 would have matched."100" ,contains andin are Simple operators too. Others includeregex ,startsWith ,endsWith for a type check, andis ;!= and&& combine conditions in one expression.|| is the typed builder form of the same test, andheader("amount").isGreaterThan(100) combines builder predicates.PredicateBuilder.and(...)- The XPath predicate read the
attribute from the XML body. It converted thetype body to a DOM document first, which needs camel-xml-jaxp on the classpath; without it, the predicate fails withString .NoTypeConversionAvailableException - The Java lambda matched both messages, since both bodies are longer than 20 characters. A lambda is a
because the interface has one method,Predicate .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()choice()end()
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();
}
}
direct:withoutEnd
audit step ran for basic
direct:withEnd
audit step ran for gold
audit step ran for basic
- Without
, the audit step ran forend() only. It became part of thebasic branch, so gold customers skipped it, and nothing in the build or the startup log says so.otherwise - With
, the audit step ran for both, because it now follows the whole choice.end()
The same rule applies to filter()split()multicast()whenendChoice()whenend()end()
Message filter
filter()end()
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();
}
}
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
ran the step inside the filter, but both messages reached the step afterpay #1 . The filter skips its own steps; it does not end the exchange.end() - In the second route, the filter matches what should be dropped and calls
, which ends the exchange there.stop() never reached the payment step, andlogin #4 did.pay #3
Use filter(...).stop()
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:
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();
}
}
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
. Each recipient received its own copy of the exchange.end() - The second message went only to push, since the list is evaluated for every message.
- The third list reached email, and
was skipped silently, becausefax:office was set. Without it, the unknown scheme fails the exchange withignoreInvalidEndpoints() .ResolveEndpointFailedException
The expression may return a delimited string, as here (the delimiter is a comma by default and can be changed with delimiter(";")parallelProcessing()AggregationStrategymulticast()
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()to()
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();
}
}
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
from the header once and ran the steps in order, so the body becamedirect:validate,direct:ship .order+validated+shipped - The dynamic router called
before every step. It returnednextStep , thendirect:validate , thendirect:price , and finallydirect:ship , which ends the routing. The bean keeps its position in an exchange property, because the router calls the same method again after each step.null evaluated the header and sent the message totoD("direct:${header.target}") , so the reply isdirect:price .order+priced did not evaluate anything. It sent the message to an endpoint literally namedto("mock:${header.target}") , which appears in the endpoint registry as${header.target} , and the body came back unchanged. No error was raised, so the message simply went to the wrong place.mock://$%7Bheader.target%7D
A dynamic router that never returns nulltoD()CamelHttpPath
Choosing a routing pattern
| Need | Use |
|---|---|
| Send each message to one of a few known places | choice()otherwise() |
| Skip some steps for some messages | filter() |
| Drop messages that should not be processed | filter(...).stop() |
| Send copies to a fixed set of places | multicast() |
| Send copies to a set chosen per message | recipientList() |
| Run a sequence of steps listed in the message | routingSlip() |
| Decide the next step after each step | dynamicRouter()null |
| One endpoint whose URI needs message data | toD() |
Most routing bugs on this page are silent: a missing end()whento()${...}