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, kafka or timer. Each component lives in its own jar.
  • Endpoint: one configured address of a component, written as a URI. file:inbox?noop=true is the file component pointed at the inbox directory with one option set.
  • 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 log to split, becomes a processor when the route starts.

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() is the content-based router, split() the splitter, aggregate() the aggregator. Learning Camel is largely learning which pattern solves which problem.

The main ways to write Camel routes
DSLModuleBest for
Java DSL (RouteBuilder)camel-coreRoutes kept with Java code, compiled and refactored by the IDE
YAML DSLcamel-yaml-dslRoutes as configuration files, Camel JBang and the Kaoto visual editor
XML DSLcamel-xml-io-dslTeams that already keep routes in XML
Spring XMLcamel-spring-xmlOlder applications wired with Spring XML files
Rest DSLcamel-restDeclaring 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 (direct, seda, timer, log, mock, file, bean) and Logback, with a logback.xml that prints LEVEL [thread] logger - message and turns Camel's own startup logging down to WARN, so the output shows only what each program does.

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 component, which lets Java code call a route like a method, so the result can be printed:

Java
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());
    }
}
Output
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 camel-1. Set your own with camel.getCamelContextExtension().setName(...), or camel.main.name in Camel Main, so that logs and JMX tell applications apart.
  • The route greet consumes from direct://greet. Camel normalised direct:greet to the scheme://path form when it created the endpoint.
  • The first log line comes from the log(...) step, whose logger name is the route id. The second comes from the log component, whose logger name is the part after log:, greetings, and which prints a summary of the exchange.
  • transform replaced the body with the result of a Simple expression, and requestBody handed that body back to the caller as Hello, Ada!.

A RouteBuilder only describes routes. Its configure() method runs once, when the routes are added, and builds a model; Camel turns the model into processors when the context starts. Code inside configure() therefore does not run per message. Per-message logic goes inside a processor, a bean or an expression such as simple(...).

The Exchange and the Message

Every step in a route reads and changes one Exchange. This program puts a header and a property on it, prints what a processor sees, then calls the same route three different ways to show what the caller gets back:

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 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();
    }
}
Output
== 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 "21", and getBody(Integer.class) 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.
  • The header customer set by the caller and the header region 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.
  • The property startedBy belongs to the exchange, not the message. Components do not send properties anywhere, so they suit values that only the route itself needs.
  • requestBody used the InOut pattern and returned the final body, 42. sendBody used InOnly and returns nothing, although the route ran the same way.
  • send(...) returned the whole exchange. Its body is 16 even though the pattern was InOnly: the pattern tells components whether a reply is expected, but it does not stop steps from changing the message.

In Camel 4, use exchange.getMessage(). The older getIn() and getOut() pair came from a model with separate request and reply messages; getOut() is deprecated. It creates a new, empty message, so a processor that sets its result there by mistake loses every header set before it.

Synchronous and asynchronous hand-off: direct and seda

Routes call each other through endpoints, and the endpoint decides the threading. direct calls the next route on the caller's thread, and seda puts the exchange on an in-memory queue that another thread takes from. The seda route here sleeps for 200 ms, so the difference is visible:

Java
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();
    }
}
Output
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 direct route ran on main, the caller's thread, and had finished before sendBody returned. A failure there would have been thrown back to the caller.
  • The seda send returned at once. The route ran later on Camel (camel-1) thread #1 - seda://async, a consumer thread that Camel created for that queue.

Use direct to split a long route into named parts that behave like method calls. Use seda to let a slow step run in the background, or to accept bursts faster than they can be processed. The seda queue lives in memory: messages waiting in it are lost if the JVM stops, so use a real broker such as Kafka or JMS when they must survive a restart. The size option bounds the queue, and concurrentConsumers sets how many threads take from it.

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:

Java
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();
    }
}
Output
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 timer URIs differ in form and in option order, yet both became timer://tick?period=500&repeatCount=3. 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.
  • The components timer, file and seda 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.
  • jms: failed with NoSuchEndpointException, because camel-jms is not on the classpath. The message names the missing jar.
  • The misspelt option perod failed with ResolveEndpointFailedException and Unknown parameters=[{perod=500}]. Camel validates every option against the endpoint's properties, so a typo fails at startup rather than being ignored.

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}} in the URI, as the next section shows.

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:

Java
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");
    }
}
Output
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 Camel (ticker-app) thread #2 - timer://tick. The thread name shows the context name set with withName, and each timer name gets a thread of its own, as the timer page explains.
  • {{app.greeting}} was replaced with tick when the route started. In a real application the value comes from application.properties on the classpath, environment variables or system properties.
  • withDurationMaxMessages(3) told Main to shut down after three exchanges had completed, and run then returned exit code 0. Without it, run blocks until the JVM receives a shutdown signal such as Ctrl+C.

Main also discovers RouteBuilder classes by package scan (camel.main.basePackageScan) and binds beans with main.bind(name, bean). In Spring Boot, camel-spring-boot-starter does the same job: every RouteBuilder annotated with @Component is added to a context that starts and stops with the application. The Camel with Spring Boot page covers that setup.

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:

Java
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());
        }
    }
}
Output
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 greet consuming from direct://greet, 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.
  • The log lines and the reply, Hello, Ada!, match the first program's output exactly: once loaded, a YAML route and a Java route are the same kind of route objects.
  • The step transfrom was rejected with UnknownNodeIdException 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.

The file uses the canonical notation, in which every step is a map of named options, such as log with message. The YAML DSL also accepts a compact notation, for example - log: "received ${body}" and - to: log:greetings. In a trial run with the compact form, Camel 4.23 loaded the same route but logged a warning that recommends the canonical notation and the command camel validate normalize to convert a file.

Camel Main loads such files from the locations set in camel.main.routesIncludePattern, for example classpath:routes/*.yaml. YAML routes suit teams that change routes more often than code, and they can be reloaded without a rebuild. Java routes are easier to test, debug and refactor. Many applications mix the two, keeping complex logic in Java beans that YAML routes call.

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 seda queues. Two routes that both consume from seda:orders share one queue.
  • A missing component fails at startup: a route using kafka: without camel-kafka on the classpath stops the whole context from starting, as the jms: line above shows.
  • Static URIs: to("file:out/${header.name}") does not evaluate the Simple expression. Use toD(...) for a URI built from the message. The 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

Common first tasks and where they are covered
TaskCamel featurePage
Send messages to different places by contentchoice(), filter(), recipientList()Routing
Broadcast, enrich, deduplicate, load balanceMulticast, wire tap, enricher, idempotent consumerEIP patterns
Process the items of a batch one by onesplit()Splitter
Combine related messages into oneaggregate()Aggregator
Protect a slow downstream systemthrottle()Throttler
Run something on a scheduletimer, schedulerTimer
Retry and handle failuresonException, dead letter channelError handling
Convert JSON, XML and CSVmarshal(), unmarshal()Data formats
Test routesMock endpoints, AdviceWithTesting

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.