Apache Camel: how routes, endpoints and exchanges fit together
Apache Camel is a Java library that moves messages between systems along routes you describe in a few lines of code. This page explains the pieces underneath, the CamelContext, components, endpoints and the Exchange, then runs each one with Camel 4.23 so you can see what Camel actually does with a message.
Contents
What Camel is and how it works
Most applications have to talk to other systems: read files dropped by a partner, call an HTTP API, consume a Kafka topic, write to a database. The code for each connection is different, but the shape of the work is the same. A message arrives from somewhere, is checked, changed or split, and is sent somewhere else. Apache Camel is a library for that shape. You describe the flow as a route, and Camel supplies the connectors, the threading and the error handling.
Camel is not a server or a broker. It is a set of jars that runs inside your own JVM, in a plain Java program, in Spring Boot or in Quarkus. Six ideas cover almost everything it does:
- CamelContext: the runtime. It holds the routes, the components, the type converters and the thread pools, and starts and stops them together.
- Route: one flow, from a single consumer to a chain of processing steps. Each route starts with
.from(...) - Component: a connector to one kind of system, such as
,file ,http orkafka . Each component lives in its own jar.timer - Endpoint: one configured address of a component, written as a URI.
is thefile:inbox?noop=true component pointed at thefile directory with one option set.inbox - Exchange: the container that travels along a route. It holds the message (body and headers), exchange properties, the message exchange pattern and any exception.
- Processor: a step that works on the exchange. Every DSL call, from
tolog , becomes a processor when the route starts.split
The processing steps are mostly Enterprise Integration Patterns (EIPs), the catalogue of messaging patterns from the 2003 book by Gregor Hohpe and Bobby Woolf. Camel names its DSL methods after them: choice()split()aggregate()
| DSL | Module | Best for |
|---|---|---|
Java DSL (RouteBuilder | camel-core | Routes kept with Java code, compiled and refactored by the IDE |
| YAML DSL | camel-yaml-dsl | Routes as configuration files, Camel JBang and the Kaoto visual editor |
| XML DSL | camel-xml-io-dsl | Teams that already keep routes in XML |
| Spring XML | camel-spring-xml | Older applications wired with Spring XML files |
| Rest DSL | camel-rest | Declaring REST endpoints that hand requests to routes |
Every example on this page and the other Camel pages is a complete program using Camel 4.23, which needs Java 17 or later; the examples run on Java 21. The classpath holds camel-main, the core components (directsedatimerlogmockfilebeanlogback.xmlLEVEL [thread] logger - messageWARN
A first route
The smallest useful Camel program needs a context, one route and a way to send it a message. This one uses the direct
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class FirstRoute {
static class GreetingRoutes extends RouteBuilder {
@Override
public void configure() {
from("direct:greet")
.routeId("greet")
.log("received ${body}")
.transform(simple("Hello, ${body}!"))
.to("log:greetings?showHeaders=false");
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new GreetingRoutes());
camel.start();
System.out.println("Camel " + camel.getVersion() + ", context " + camel.getName());
for (Route route : camel.getRoutes()) {
System.out.println("route " + route.getRouteId() + " consumes from "
+ route.getEndpoint().getEndpointUri());
}
ProducerTemplate template = camel.createProducerTemplate();
String reply = template.requestBody("direct:greet", "Ada", String.class);
System.out.println("reply: " + reply);
camel.stop();
System.out.println("status after stop: " + camel.getStatus());
}
}
Camel 4.23.0, context camel-1
route greet consumes from direct://greet
INFO [main] greet - received Ada
INFO [main] greetings - Exchange[ExchangePattern: InOut, BodyType: String, Body: Hello, Ada!]
reply: Hello, Ada!
status after stop: Stopped
- The context took the default name
. Set your own withcamel-1 , orcamel.getCamelContextExtension().setName(...) in Camel Main, so that logs and JMX tell applications apart.camel.main.name - The route
consumes fromgreet . Camel normaliseddirect://greet to thedirect:greet form when it created the endpoint.scheme://path - The first log line comes from the
step, whose logger name is the route id. The second comes from thelog(...) component, whose logger name is the part afterlog ,log: , and which prints a summary of the exchange.greetings replaced the body with the result of a Simple expression, andtransform handed that body back to the caller asrequestBody .Hello, Ada!
A RouteBuilderconfigure()configure()simple(...)
The Exchange and the Message
Every step in a route reads and changes one Exchange
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 ExchangeModel {
static class OrderRoutes extends RouteBuilder {
@Override
public void configure() {
from("direct:order")
.setHeader("region", constant("EU"))
.setProperty("startedBy", constant("order-route"))
.process(exchange -> {
System.out.println("pattern : " + exchange.getPattern());
System.out.println("body type : "
+ exchange.getMessage().getBody().getClass().getSimpleName());
System.out.println("headers : " + exchange.getMessage().getHeaders());
System.out.println("property : " + exchange.getProperty("startedBy"));
int qty = exchange.getMessage().getBody(Integer.class);
exchange.getMessage().setBody(qty * 2);
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new OrderRoutes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("== requestBody (InOut)");
Object reply = template.requestBodyAndHeader("direct:order", "21", "customer", "c-7");
System.out.println("caller got : " + reply);
System.out.println("== sendBody (InOnly)");
template.sendBodyAndHeader("direct:order", "5", "customer", "c-8");
System.out.println("sendBody returns void");
System.out.println("== send(Exchange) to inspect the whole result");
Exchange done = template.send("direct:order", e -> e.getMessage().setBody("8"));
System.out.println("result body : " + done.getMessage().getBody());
System.out.println("property : " + done.getProperty("startedBy"));
System.out.println("failed? : " + done.isFailed());
camel.stop();
}
}
== requestBody (InOut)
pattern : InOut
body type : String
headers : {customer=c-7, region=EU}
property : order-route
caller got : 42
== sendBody (InOnly)
pattern : InOnly
body type : String
headers : {customer=c-8, region=EU}
property : order-route
sendBody returns void
== send(Exchange) to inspect the whole result
pattern : InOnly
body type : String
headers : {region=EU}
property : order-route
result body : 16
property : order-route
failed? : false
- The body arrived as the
String , and"21" turned it into the number 21. Camel's type converter registry did that; it knows hundreds of conversions, between strings, numbers, byte arrays, streams, files and XML types.getBody(Integer.class) - The header
set by the caller and the headercustomer set by the route both sit in the message. Headers belong to the message, and components map them to and from the outside world, for example to HTTP headers or Kafka record headers.region - The property
belongs to the exchange, not the message. Components do not send properties anywhere, so they suit values that only the route itself needs.startedBy used therequestBody pattern and returned the final body, 42.InOut usedsendBody and returns nothing, although the route ran the same way.InOnly returned the whole exchange. Its body is 16 even though the pattern wassend(...) : the pattern tells components whether a reply is expected, but it does not stop steps from changing the message.InOnly
In Camel 4, use exchange.getMessage()getIn()getOut()getOut()
Synchronous and asynchronous hand-off: direct and seda
Routes call each other through endpoints, and the endpoint decides the threading. directseda
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class DirectVsSeda {
static final CountDownLatch SEDA_DONE = new CountDownLatch(1);
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:sync")
.process(e -> System.out.println("direct route runs on: "
+ Thread.currentThread().getName()));
from("seda:async")
.process(e -> {
Thread.sleep(200);
System.out.println("seda route runs on : "
+ Thread.currentThread().getName());
SEDA_DONE.countDown();
});
}
}
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("caller thread : " + Thread.currentThread().getName());
template.sendBody("direct:sync", "a");
System.out.println("after direct send : route already finished");
template.sendBody("seda:async", "b");
System.out.println("after seda send : caller continues, route still waiting");
boolean finished = SEDA_DONE.await(5, TimeUnit.SECONDS);
System.out.println("seda route finished : " + finished);
camel.stop();
}
}
caller thread : main
direct route runs on: main
after direct send : route already finished
after seda send : caller continues, route still waiting
seda route runs on : Camel (camel-1) thread #1 - seda://async
seda route finished : true
- The
route ran ondirect , the caller's thread, and had finished beforemain returned. A failure there would have been thrown back to the caller.sendBody - The
send returned at once. The route ran later onseda , a consumer thread that Camel created for that queue.Camel (camel-1) thread #1 - seda://async
Use directsedasizeconcurrentConsumers
Components and endpoint URIs
An endpoint URI has three parts: the scheme picks the component, the path says what to connect to, and the query sets options. Camel resolves a component from the scheme the first time it sees it. This program creates a few endpoints, then makes the two mistakes everyone makes at least once:
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultCamelContext;
public class EndpointUris {
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.start();
String[] uris = {
"timer:tick?repeatCount=3&period=500",
"timer://tick?period=500&repeatCount=3",
"seda:orders?size=100",
"file:inbox?noop=true",
};
for (String uri : uris) {
Endpoint endpoint = camel.getEndpoint(uri);
System.out.printf("%-40s -> %s (%s)%n", uri, endpoint.getEndpointUri(),
endpoint.getClass().getSimpleName());
}
System.out.println("endpoints in registry: " + camel.getEndpoints().size());
System.out.println("components loaded : " + camel.getComponentNames());
try {
camel.getEndpoint("jms:queue:orders");
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
try {
camel.getEndpoint("timer:tick?perod=500");
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
camel.stop();
}
}
timer:tick?repeatCount=3&period=500 -> timer://tick?period=500&repeatCount=3 (TimerEndpoint)
timer://tick?period=500&repeatCount=3 -> timer://tick?period=500&repeatCount=3 (TimerEndpoint)
seda:orders?size=100 -> seda://orders?size=100 (SedaEndpoint)
file:inbox?noop=true -> file://inbox?noop=true (FileEndpoint)
endpoints in registry: 3
components loaded : [timer, file, seda]
NoSuchEndpointException: No endpoint could be found for: jms://queue:orders, please check your classpath contains the needed Camel component jar (the jms component is in camel-jms; add camel-jms to the classpath).
ResolveEndpointFailedException: Failed to resolve endpoint: timer://tick?perod=500 due to: Failed to resolve endpoint: timer://tick?perod=500 due to: There are 1 parameters that couldn't be set on the endpoint. Check the uri if the parameters are spelt correctly and that they are properties of the endpoint. Unknown parameters=[{perod=500}]
- The two
URIs differ in form and in option order, yet both becametimer . Camel normalises URIs by sorting the options, and endpoints are cached under the normalised URI, which is why the registry holds three endpoints for four URIs.timer://tick?period=500&repeatCount=3 - The components
,timer andfile were loaded only when first used. Camel finds them on the classpath through a small descriptor file in each component jar, so adding a component is a matter of adding its dependency.seda failed withjms: , because camel-jms is not on the classpath. The message names the missing jar.NoSuchEndpointException- The misspelt option
failed withperod andResolveEndpointFailedException . Camel validates every option against the endpoint's properties, so a typo fails at startup rather than being ignored.Unknown parameters=[{perod=500}]
Options can also be set on the component, for values shared by all its endpoints, such as a Kafka broker list. Values that change between environments belong in properties, written as placeholders such as {{db.url}}
Running Camel as an application with Camel Main
The earlier programs stop the context themselves. A real integration runs until it is told to stop. Camel Main, in camel-main, supplies that loop for plain Java: it builds the context, loads configuration, starts the routes and blocks until shutdown. The program limits the run to three messages so it ends:
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class MainApp {
static class TickRoutes extends RouteBuilder {
@Override
public void configure() {
from("timer:tick?period=200&includeMetadata=true")
.routeId("ticker")
.setBody(simple("{{app.greeting}} number ${exchangeProperty.CamelTimerCounter}"))
.log("${body}");
}
}
public static void main(String[] args) throws Exception {
Main main = new Main();
main.configure().addRoutesBuilder(new TickRoutes());
main.configure().withName("ticker-app").withDurationMaxMessages(3);
main.addInitialProperty("app.greeting", "tick");
int exitCode = main.run(args);
System.out.println("Main.run returned " + exitCode + " after "
+ main.getCamelContext().getName() + " stopped");
}
}
INFO [Camel (ticker-app) thread #2 - timer://tick] ticker - tick number 1
INFO [Camel (ticker-app) thread #2 - timer://tick] ticker - tick number 2
INFO [Camel (ticker-app) thread #2 - timer://tick] ticker - tick number 3
Main.run returned 0 after ticker-app stopped
- The timer fired every 200 ms on
. The thread name shows the context name set withCamel (ticker-app) thread #2 - timer://tick , and each timer name gets a thread of its own, as thewithNametimer page explains. was replaced with{{app.greeting}} when the route started. In a real application the value comes fromtick on the classpath, environment variables or system properties.application.properties told Main to shut down after three exchanges had completed, andwithDurationMaxMessages(3) then returned exit code 0. Without it,run blocks until the JVM receives a shutdown signal such as Ctrl+C.run
Main also discovers RouteBuildercamel.main.basePackageScanmain.bind(name, bean)RouteBuilder@Component
The same route in YAML
The Java DSL and the YAML DSL build the same route model, so a route can move between them. YAML is the format used by Camel JBang and the Kaoto visual editor, and it needs the camel-yaml-dsl module. This program writes the greeting route from the first example to a YAML file, loads it into a context with the routes loader and sends it the same message. It then loads a second file with a misspelt step name:
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Resource;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.ResourceHelper;
public class YamlRoute {
public static void main(String[] args) throws Exception {
// the greeting route from the first example, as a YAML file
Path dir = Files.createTempDirectory("routes");
Path file = Files.writeString(dir.resolve("greet.yaml"), """
- route:
id: greet
from:
uri: direct:greet
steps:
- log:
message: "received ${body}"
- transform:
expression:
simple:
expression: "Hello, ${body}!"
- to:
uri: log:greetings?showHeaders=false
""");
CamelContext camel = new DefaultCamelContext();
Resource resource = ResourceHelper.resolveResource(camel, "file:" + file);
PluginHelper.getRoutesLoader(camel).loadRoutes(resource);
camel.start();
for (Route route : camel.getRoutes()) {
System.out.println("route " + route.getRouteId() + " consumes from "
+ route.getEndpoint().getEndpointUri() + ", loaded from "
+ route.getSourceResource().getLocation().replace(dir.toString(), "<dir>"));
}
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("reply: " + template.requestBody("direct:greet", "Ada", String.class));
camel.stop();
// a typo in a step name is caught when the file is loaded, not when a message arrives
Path broken = Files.writeString(dir.resolve("broken.yaml"), """
- route:
from:
uri: direct:broken
steps:
- transfrom:
simple: "Hello, ${body}!"
""");
CamelContext second = new DefaultCamelContext();
try {
PluginHelper.getRoutesLoader(second).loadRoutes(
ResourceHelper.resolveResource(second, "file:" + broken));
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName() + ": "
+ e.getMessage().replace(dir.toString(), "<dir>").lines().findFirst().get());
}
}
}
route greet consumes from direct://greet, loaded from file:<dir>/greet.yaml
INFO [main] greet - received Ada
INFO [main] greetings - Exchange[ExchangePattern: InOut, BodyType: String, Body: Hello, Ada!]
reply: Hello, Ada!
UnknownNodeIdException: Unknown node id: transfrom
- The YAML file produced a route named
consuming fromgreet , the same as the Java route in the first program. The route also remembers the file it came from, which shows up in error messages and in tools.direct://greet - The log lines and the reply,
, match the first program's output exactly: once loaded, a YAML route and a Java route are the same kind of route objects.Hello, Ada! - The step
was rejected withtransfrom while the file was loaded, before the context started. A typo in a YAML route fails at start-up, much as a typo in the Java DSL fails at compile time.UnknownNodeIdException
The file uses the canonical notation, in which every step is a map of named options, such as logmessage- log: "received ${body}"- to: log:greetingscamel validate normalize
Camel Main loads such files from the locations set in camel.main.routesIncludePatternclasspath:routes/*.yaml
Things that surprise new Camel users
- Endpoints are cached: the same URI always returns the same endpoint object, which matters for components with state such as
queues. Two routes that both consume fromseda share one queue.seda:orders - A missing component fails at startup: a route using
without camel-kafka on the classpath stops the whole context from starting, as thekafka: line above shows.jms: - Static URIs:
does not evaluate the Simple expression. Useto("file:out/${header.name}") for a URI built from the message. ThetoD(...)routing page shows both running. - Errors and redelivery: by default a failed step stops the exchange and the error goes back to the consumer, without retries. The
error handling page explains redelivery and dead letter channels. - Thread safety: a processor or bean is shared by every exchange that passes through it, on whatever threads the route uses. Keep per-message state in the exchange, not in fields.
Choosing where to start
| Task | Camel feature | Page |
|---|---|---|
| Send messages to different places by content | choice()filter()recipientList() | |
| Broadcast, enrich, deduplicate, load balance | Multicast, wire tap, enricher, idempotent consumer | |
| Process the items of a batch one by one | split() | |
| Combine related messages into one | aggregate() | |
| Protect a slow downstream system | throttle() | |
| Run something on a schedule | timerscheduler | |
| Retry and handle failures | onException | |
| Convert JSON, XML and CSV | marshal()unmarshal() | |
| Test routes | Mock endpoints, AdviceWith |
For a plain Java service, start with Camel Main; for an application already on Spring Boot, start with the Spring Boot starter. In both, write routes in the Java DSL first, because the compiler and the debugger help most while you are learning what each step does to the exchange.