Enterprise Integration Patterns in Camel, shown running
Camel implements the Enterprise Integration Patterns catalogue as DSL methods, so most integration problems have a ready-made step. This page explains how the patterns are grouped, then runs six of the most used ones with Camel 4.23: multicast, wire tap, content enricher, idempotent consumer, resequencer and load balancer, including the copy and duplicate traps that catch people out.
Contents
What the Enterprise Integration Patterns are Multicast: the same message to several endpoints Wire tap: a side copy that does not wait Content enricher: enrich and pollEnrich Idempotent consumer: processing each message once Resequencer: putting messages back in order Load balancer: spreading work across endpoints Choosing a pattern
What the Enterprise Integration Patterns are
Enterprise Integration Patterns, the 2003 book by Gregor Hohpe and Bobby Woolf, named the recurring problems of connecting systems through messages: how to send one message to several places, how to combine replies, how to drop duplicates, how to restore order. Camel was built around that catalogue. Each pattern is a DSL method, and each method becomes a processor that works on the exchange.
The patterns fall into a few groups, and knowing the group helps you find the right one:
| Group | Patterns (Camel DSL) | Solves |
|---|---|---|
| Routing | choicefilterrecipientListroutingSlipdynamicRouter | Where a message goes |
| Fan-out and fan-in | multicastsplitaggregatewireTap | One message to many, or many to one |
| Transformation | transformenrichpollEnrichmarshalclaimCheck | Changing or completing the content |
| Flow control | throttledelayresequenceloopsample | Rate, timing and order |
| Reliability | idempotentConsumercircuitBreakerloadBalancesaga | Duplicates, failures and spreading load |
Almost every pattern makes the same three decisions, and most surprises come from the defaults:
- Copies: does each branch get its own copy of the exchange, and how deep is that copy?
- Threads: do the branches run one after another on the caller's thread, or in parallel on a pool?
- Result: which message continues afterwards? Patterns that fan out take an
to decide.AggregationStrategy
Routing, splitting, aggregating and throttling have their own pages, linked at the end. This page covers the other patterns most applications need. The examples run with Camel 4.23 on Java 21, with camel-main and the core components on the classpath.
Multicast: the same message to several endpoints
Multicast sends a copy of the message to a fixed list of endpoints and combines their replies. A product page needing stock, price and reviews from three services is the classic case. Each service here takes 300 ms, so the effect of parallelProcessing()
import org.apache.camel.AggregationStrategy;
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 MulticastDemo {
static class JoinReplies implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String joined = oldExchange.getMessage().getBody(String.class) + " | "
+ newExchange.getMessage().getBody(String.class);
oldExchange.getMessage().setBody(joined);
return oldExchange;
}
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:sequential")
.multicast(new JoinReplies())
.to("direct:stock", "direct:price", "direct:reviews")
.end();
from("direct:parallel")
.multicast(new JoinReplies()).parallelProcessing()
.to("direct:stock", "direct:price", "direct:reviews")
.end();
from("direct:stock").delay(300).syncDelayed().setBody(simple("stock(${body})=12"));
from("direct:price").delay(300).syncDelayed().setBody(simple("price(${body})=9.99"));
from("direct:reviews").delay(300).syncDelayed().setBody(simple("reviews(${body})=4.5"));
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
template.requestBody("direct:parallel", "warm-up");
for (String mode : new String[] {"sequential", "parallel"}) {
long start = System.nanoTime();
String reply = template.requestBody("direct:" + mode, "book-7", String.class);
long ms = (System.nanoTime() - start) / 1000000;
System.out.println(mode + ": " + reply);
System.out.println(" took about " + Math.round(ms / 300.0) + " x 300 ms");
}
camel.stop();
}
}
sequential: stock(book-7)=12 | price(book-7)=9.99 | reviews(book-7)=4.5
took about 3 x 300 ms
parallel: stock(book-7)=12 | price(book-7)=9.99 | reviews(book-7)=4.5
took about 1 x 300 ms
- Both runs produced the same reply, joined in the order of the
list. Withto(...) , replies arrive in any order, but Camel still aggregates them in list order unlessparallelProcessing() is set.streaming() - Sequential multicast took about three times 300 ms, because each call waited for the previous one. In parallel, the three calls overlapped and the whole multicast took about 300 ms (rough comparison, on a shared Linux container).
receivesJoinReplies asnull for the first reply, then the result so far together with each further reply. That is the contract of everyoldExchange in Camel.AggregationStrategy
Without a strategy, the body that continues after the multicast is the reply of the last endpoint, not the original message, which surprises people who use multicast only to notify other routes. Use AggregationStrategies.useOriginal()stopOnException()
Wire tap: a side copy that does not wait
A wire tap sends a copy of the exchange to another endpoint on a separate thread, and the main route carries on without waiting for it. It suits auditing and monitoring. The tap here changes a header and empties the body, which is a mutable List
import java.util.ArrayList;
import java.util.List;
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 WireTapDemo {
static final CountDownLatch TAPPED = new CountDownLatch(1);
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:order")
.setHeader("stage", constant("received"))
.wireTap("direct:audit")
.process(e -> {
TAPPED.await(5, TimeUnit.SECONDS);
System.out.println("main route thread : " + Thread.currentThread().getName());
System.out.println("main route header : " + e.getMessage().getHeader("stage"));
System.out.println("main route body : " + e.getMessage().getBody());
});
from("direct:audit")
.process(e -> {
System.out.println("audit thread : " + Thread.currentThread().getName());
e.getMessage().setHeader("stage", "audited");
List<?> lines = e.getMessage().getBody(List.class);
System.out.println("audit sees body : " + lines);
lines.clear();
TAPPED.countDown();
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
List<String> lines = new ArrayList<>(List.of("book", "pen"));
template.sendBody("direct:order", lines);
System.out.println("caller's list now : " + lines);
camel.stop();
}
}
audit thread : Camel (camel-1) thread #1 - WireTap
audit sees body : [book, pen]
main route thread : main
main route header : received
main route body : []
caller's list now : []
- The audit route ran on
, while the main route stayed onCamel (camel-1) thread #1 - WireTap .main - The tap set the header
tostage , but the main route still sawaudited . The copy has its own headers map.received - The tap cleared the list, and the main route and the caller both saw
. The copy is shallow: both exchanges point to the same body object, so a change to a mutable body is visible everywhere.[]
Keep tapped bodies immutable, such as a Stringbyte[]onPrepare(...)InputStreamString
Content enricher: enrich and pollEnrich
The content enricher calls another endpoint and merges its result into the current message. The difference from a plain to()to()enrich()pollEnrich()
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class EnricherDemo {
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:withEnrich")
.enrich("direct:customerService", (original, resource) -> {
String name = resource.getMessage().getBody(String.class);
original.getMessage().setHeader("customerName", name);
return original;
})
.setBody(simple("${body} for ${header.customerName}"));
from("direct:withTo")
.to("direct:customerService")
.setBody(simple("${body} for ${header.customerName}"));
from("direct:customerService")
.setBody(simple("Customer ${header.customerId}"));
from("direct:withPollEnrich")
.pollEnrich("seda:latestRates", 500)
.setBody(simple("rate=${body}"));
}
}
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("enrich : " + template.requestBodyAndHeader("direct:withEnrich",
"order 17", "customerId", "c-42"));
System.out.println("to : " + template.requestBodyAndHeader("direct:withTo",
"order 17", "customerId", "c-42"));
template.sendBody("seda:latestRates", "1.09");
System.out.println("pollEnrich: " + template.requestBody("direct:withPollEnrich", "x"));
long start = System.nanoTime();
Object empty = template.requestBody("direct:withPollEnrich", "x");
long ms = (System.nanoTime() - start) / 1000000;
String waited = ms >= 500 ? "the full" : "less than";
System.out.println("pollEnrich: " + empty + " (waited " + waited + " 500 ms timeout)");
camel.stop();
}
}
enrich : order 17 for Customer c-42
to : Customer c-42 for
pollEnrich: rate=1.09
pollEnrich: rate= (waited the full 500 ms timeout)
- With
, the strategy copied the customer name into a header and kept the original body, so the result isenrich() .order 17 for Customer c-42 - With
, the customer service's reply replaced the body, and nothing set the header, so the result isto() : the order text is lost and the name is empty.Customer c-42 for - The first
took the message waiting onpollEnrich . The second found the queue empty, waited the full 500 ms, and continued with an empty body.seda:latestRates
enrich()pollEnrich()
Idempotent consumer: processing each message once
Most transports deliver at least once: a broker redelivers after a timeout, a partner resends a file, a user clicks twice. An idempotent consumer keeps the keys it has seen in a repository and skips messages whose key is already there. This program sends a duplicate, a payment that fails and is retried, and a duplicate that is flagged instead of dropped:
import java.util.TreeSet;
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;
import org.apache.camel.support.KeyValueIdempotentRepository;
import org.apache.camel.support.MemoryKeyValueRepository;
public class IdempotentDemo {
static final MemoryKeyValueRepository STORE = new MemoryKeyValueRepository();
static final KeyValueIdempotentRepository SEEN = new KeyValueIdempotentRepository(STORE);
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
from("direct:payments")
.idempotentConsumer(header("paymentId"), SEEN)
.process(e -> {
String body = e.getMessage().getBody(String.class);
if (body.contains("fail")) {
throw new IllegalStateException("bank timeout");
}
System.out.println(" charged " + e.getMessage().getHeader("paymentId"));
})
.end();
from("direct:flagged")
.idempotentConsumer(header("paymentId"), SEEN).skipDuplicate(false)
.filter(exchangeProperty(Exchange.DUPLICATE_MESSAGE).isEqualTo(true))
.process(e -> System.out.println(" duplicate flagged: "
+ e.getMessage().getHeader("paymentId")))
.stop()
.end()
.process(e -> System.out.println(" charged " + e.getMessage()
.getHeader("paymentId")))
.end();
}
}
static void send(ProducerTemplate template, String endpoint, String id, String body) {
try {
template.sendBodyAndHeader(endpoint, body, "paymentId", id);
} catch (Exception e) {
System.out.println(" " + id + " failed: " + e.getCause().getMessage());
}
}
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("p-1 twice, p-2 once:");
send(template, "direct:payments", "p-1", "ok");
send(template, "direct:payments", "p-1", "ok");
send(template, "direct:payments", "p-2", "ok");
System.out.println("p-3 fails, then is retried:");
send(template, "direct:payments", "p-3", "fail");
send(template, "direct:payments", "p-3", "ok");
System.out.println("skipDuplicate(false):");
send(template, "direct:flagged", "p-2", "ok");
send(template, "direct:flagged", "p-4", "ok");
System.out.println("keys in repository: " + new TreeSet<>(STORE.keys()));
camel.stop();
}
}
p-1 twice, p-2 once:
charged p-1
charged p-2
p-3 fails, then is retried:
p-3 failed: bank timeout
charged p-3
skipDuplicate(false):
duplicate flagged: p-2
charged p-4
keys in repository: [idempotent:p-1, idempotent:p-2, idempotent:p-3, idempotent:p-4]
- The second
was skipped without any output, and the caller got no error: duplicates are dropped silently.p-1 failed, and its retry was charged. When an exchange fails, the consumer removes its key again (p-3 defaults to true), so a failed message can be retried.removeOnFailure- With
, the duplicateskipDuplicate(false) was not skipped but went through with the propertyp-2 set to true, so the route could log it and stop.CamelDuplicateMessage was new and was charged.p-4 - The repository held four keys at the end.
stored them with the prefixKeyValueIdempotentRepository in aidempotent: .MemoryKeyValueRepository
Camel 4.23 deprecated MemoryIdempotentRepositoryKeyValueIdempotentRepositoryKeyValueRepository
The key is added when the message arrives (eager
Resequencer: putting messages back in order
Parallel processing and partitioned transports deliver messages out of order. The resequencer holds messages and releases them sorted by an expression, here a sequence number header. The batch mode collects a group and sorts it; the stream mode releases each message as soon as its predecessor has gone, and has to decide how long to wait for a missing one:
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.component.mock.MockEndpoint;
public class ResequencerDemo {
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:batch")
.resequence(header("seq")).batch().size(5).timeout(1000)
.to("mock:batchOut");
from("direct:stream")
.resequence(header("seq")).stream().capacity(100).timeout(300)
.to("mock:streamOut");
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
MockEndpoint batchOut = camel.getEndpoint("mock:batchOut", MockEndpoint.class);
batchOut.setExpectedCount(5);
MockEndpoint streamOut = camel.getEndpoint("mock:streamOut", MockEndpoint.class);
streamOut.setExpectedCount(4);
long batchStart = System.nanoTime();
List<Long> arrival = List.of(3L, 1L, 5L, 2L, 4L);
System.out.println("arrival order : " + arrival);
for (long seq : arrival) {
template.sendBodyAndHeader("direct:batch", "msg" + seq, "seq", seq);
}
batchOut.assertIsSatisfied(3000);
long batchMs = (System.nanoTime() - batchStart) / 1000000;
System.out.println("batch output : " + bodies(batchOut));
System.out.println("released before the 1000 ms timeout: " + (batchMs < 1000));
List<Long> withGap = List.of(2L, 1L, 4L, 5L);
System.out.println("stream input : " + withGap + " (3 never arrives)");
long start = System.nanoTime();
for (long seq : withGap) {
template.sendBodyAndHeader("direct:stream", "msg" + seq, "seq", seq);
}
streamOut.assertIsSatisfied(3000);
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("stream output : " + bodies(streamOut));
System.out.println("waited for the gap: " + (ms >= 300 ? "yes, at least" : "no, under")
+ " the 300 ms timeout");
camel.stop();
}
static List<String> bodies(MockEndpoint mock) {
return mock.getExchanges().stream()
.map(e -> e.getMessage().getBody(String.class)).toList();
}
}
arrival order : [3, 1, 5, 2, 4]
batch output : [msg1, msg2, msg3, msg4, msg5]
released before the 1000 ms timeout: true
stream input : [2, 1, 4, 5] (3 never arrives)
stream output : [msg1, msg2, msg4, msg5]
waited for the gap: yes, at least the 300 ms timeout
- The batch resequencer received 3, 1, 5, 2, 4 and released 1 to 5 in order. It released them as soon as the batch held its
, before the 1000 ms timeout.size(5) - The stream resequencer released 1 and 2 at once. Number 3 never arrived, so it held 4 and 5 until the 300 ms timeout passed, then released them, skipping the gap.
Batch mode suits reports and other cases where a group of messages arrives together. Stream mode suits continuous flows with gap-free sequence numbers; its expression must return a number, and its capacity
Load balancer: spreading work across endpoints
The load balancer sends each message to one of several endpoints. Three strategies show the common choices: round robin, weighted round robin with weights 3 and 1, and failover from a server that always fails:
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class LoadBalancerDemo {
static final List<String> LOG = new ArrayList<>();
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
from("direct:roundRobin")
.loadBalance().roundRobin()
.to("direct:a", "direct:b", "direct:c")
.end();
from("direct:weighted")
.loadBalance().weighted(true, "3,1")
.to("direct:a", "direct:b")
.end();
from("direct:failover")
.loadBalance().failover(IllegalStateException.class)
.to("direct:down", "direct:b")
.end();
from("direct:a").process(e -> LOG.add("a"));
from("direct:b").process(e -> LOG.add("b"));
from("direct:c").process(e -> LOG.add("c"));
from("direct:down").process(e -> {
LOG.add("down!");
throw new IllegalStateException("server down");
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
for (String balancer : new String[] {"roundRobin", "weighted", "failover"}) {
LOG.clear();
int count = balancer.equals("failover") ? 3 : 8;
for (int i = 0; i < count; i++) {
template.sendBody("direct:" + balancer, i);
}
System.out.printf("%-10s %d messages -> %s%n", balancer, count, LOG);
}
camel.stop();
}
}
roundRobin 8 messages -> [a, b, c, a, b, c, a, b]
weighted 8 messages -> [a, b, a, a, a, b, a, a]
failover 3 messages -> [down!, b, down!, b, down!, b]
- Round robin sent eight messages to a, b, c in turn, so
anda got three each andb two.c - Weighted round robin with
sent six messages to"3,1" and two toa , the 3:1 ratio of the weights.b - Failover tried
for every message, caught thedown and moved toIllegalStateException . Every message ended up atb , but each one paid for a failed attempt first.b
Plain failover()failover(-1, false, true)errorHandler(defaultErrorHandler().logExhausted(false))randomstickytopic
Choosing a pattern
| Problem | Pattern | Watch out for |
|---|---|---|
| Call several services and combine the answers | multicast()parallelProcessing() | Without a strategy, the last reply continues |
| Audit or monitor without slowing the route | wireTap() | Shallow copy of mutable bodies |
| Add data from another service to the message | enrich() | to() |
| Read a file or queue in the middle of a route | pollEnrich() | The default waits forever |
| Ignore redelivered or resent messages | idempotentConsumer() | In-memory keys are lost on restart |
| Restore order after parallel processing | resequence() | Held messages are lost on a crash |
| Spread load or survive one endpoint failing | loadBalance() | Plain failover always tries the first endpoint first |
The remaining core patterns have their own pages: