Apache Camel Conditional Routing – Apache Camel条件性路由

最后修改: 2022年 9月 2日

1. Overview


Apache Camel is a powerful open-source integration framework implementing several of the known Enterprise Integration Patterns.

Apache Camel是一个强大的开源集成框架,实现了几个已知的企业集成模式

Typically when working with message routing using Camel, we’ll want a way to process messages differently based on their content. For this, Camel provides a powerful feature called the Content Based Router from the collection of EIP patterns.


In this tutorial, we’ll take a look at several ways we can route messages based on some condition.


2. Dependencies


All we’ll need to get started is the camel-spring-boot-starter added to our pom.xml:



Then, we’ll need to add the camel-test-spring-junit5 dependency to our pom.xml:



As the name suggests, this dependency is specifically for our unit tests.


3. Defining a Simple Camel Spring Boot Application

3.定义一个简单的Camel Spring Boot应用程序

Throughout this tutorial, the focus of our examples will be a simple Apache Camel Spring Boot application.

在本教程中,我们的例子的重点将是一个简单的Apache Camel Spring Boot应用程序。

So let’s start by defining our application entry point:


public class ConditionalRoutingSpringApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConditionalRoutingSpringApplication.class, args);

As we can see, this is a standard Spring Boot application.

我们可以看到,这是一个标准的Spring Boot应用程序。

4. Conditional Routing


To quickly recap, a route in Apache Camel is a fundamental building block, normally formed of a sequence of steps, executed in order by Camel, that consumes and processes a message.

简单地说,Apache Camel中的路线是一个基本构件,通常由一系列步骤组成,由Camel按顺序执行,用于消费和处理消息。

For example, a route will typically receive a message, using a consumer perhaps from a file on disk or a message queue. Then, Camel executes the rest of the steps in the route, which either processes the message somehow or sends it to other endpoints.


Without a doubt, we’ll want a way to conditionally route a message based on some fact. For this, Camel provides the choice and when constructs. We can think of this as the equivalent of the if-else statement in Java.


With that in mind, let’s go ahead and create our first route with some conditional logic.


5. Creating a Route


In this example, we’ll define an elementary route with some conditional logic based on the contents of the message body received:


public class ConditionalBodyRouter extends RouteBuilder {

    public void configure() throws Exception {
              .setBody(simple("Goodbye, Baeldung!"))

As we can see in our trivial example, we configure our route to consume messages from a direct endpoint called start-conditional.


Now let’s walk through the key parts of our route:


  • First, we begin the route using the choice() method – this tells Camel that the following lines will contain some conditions to evaluate
  • Next, the when() method indicates a new condition to be evaluated – in this example, we simply check to see if the message body contains the string Baeldung. We can add as many when conditions as we need
  • To conclude our route, we use the otherwise() method to define what to do when none of the previous when conditions are met.
  • Finally, the route terminates using the end() method, which closes the choice block.

To summarise, when we run our route, if our message body contains the string Baeldung, we’ll set the message body to Goodbye, Baeldung! and send the result to a mock endpoint called result-body.

总而言之,当我们运行我们的路由时,如果我们的消息体包含字符串Baeldung,我们将把消息体设置为Goodbye, Baeldung!并将结果发送到一个名为result-body模拟端点

Alternatively, we’ll just route the original message to our mock endpoint.


6. Testing the Route


With the last section in mind, let’s go ahead and write a unit test to explore how our route behaves:


class ConditionalBodyRouterUnitTest {

    private ProducerTemplate template;

    private MockEndpoint mock;

    void whenSendBodyWithBaeldung_thenGoodbyeMessageReceivedSuccessfully() throws InterruptedException {
        mock.expectedBodiesReceived("Goodbye, Baeldung!");

        template.sendBody("direct:start-conditional", "Hello Baeldung Readers!");


As we can see, our test consists of three simple steps:


  • First, let’s set an expectation that our mock endpoint will receive the given message body
  • Then we’ll send a message to our direct:start-conditional endpoint using our template. Note, we’ll ensure our message body contains the string Baeldung
  • To conclude our test, we use the assertIsSatisfied method to validate that our initial expectation on our mock endpoint has been satisfied

This test confirms that our conditional routing is working correctly. Awesome!


Be sure to see our previous tutorial to learn more about how to write reliable, self-contained unit tests for our Camel routes.


7. Building Other Conditional Predicates


So far, we’ve explored one option on how to build our when predicate – inspecting the message body of our exchange. However, there are several other options available to us.

到目前为止,我们已经探讨了如何建立我们的当谓词的一个选项 – 检查我们交换的消息体。然而,我们还有其他几种选择。

For example, we can also control our conditions by inspecting the value of a given message header:


public class ConditionalHeaderRouter extends RouteBuilder {

    public void configure() throws Exception {
                .setHeader("favourite", simple("Apples"))
                .setHeader("favourite", header("fruit"))

This time around, we’ve modified the when method to look at the value of a header called fruit. It is also perfectly possible to use the Simple language Camel provides in our when conditions.

这一次,我们修改了when方法,以查看一个名为fruit的头的值。也完全可以在我们的when条件中使用Simple language Camel提供的语言。

8. Working With Java Beans 

8.使用Java Bean

Moreover, we can also use the Camel Bean language when we want to use the result of a Java method call in our predicates.

此外,当我们想在谓词中使用Java方法调用的结果时,我们也可以使用Camel Bean语言

First, we need to create a Java bean containing a method that returns a boolean:

首先,我们需要创建一个Java Bean,包含一个返回布尔值的方法。

public class FruitBean {

    public static boolean isApple(Exchange exchange) {
        return "Apple".equals(exchange.getIn().getHeader("fruit"));

Here we also optionally add the Exchange as an argument so Camel will pass the Exchange to our method automatically.


Then we can go ahead and use our FruitBean from our when block:


public class ConditionalBeanRouter extends RouteBuilder {

    public void configure() throws Exception {
              .when(method(FruitBean.class, "isApple"))
                .setHeader("favourite", simple("Apples"))
                .setHeader("favourite", header("fruit"))

9. Conclusion


In this article, we learned how we could route messages based on some kind of condition in our routes. First, we created a simple Camel application with one route to inspect the message body.


Then we learned about several other techniques for building predicates in our routes using message headers and Java beans.


As always, the full source code of the article is available over on GitHub.