Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Apache Camel Developer's Cookbook
Apache Camel Developer's Cookbook

Apache Camel Developer's Cookbook: For Apache Camel developers, this is the book you'll always want to have handy. It's stuffed full of great recipes that are designed for quick practical application. Expands your Apache Camel abilities immediately.

eBook
R$80 R$245.99
Paperback
R$306.99
Subscription
Free Trial
Renews at R$50p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Apache Camel Developer's Cookbook

Chapter 1. Structuring Routes

In this chapter, we will cover the following recipes:

  • Using Camel in a Java application
  • Embedding Camel in a Spring application
  • Using Camel components
  • Reusing routing logic by connecting routes
  • Asynchronously connecting routes
  • Spanning Camel contexts within a single Java process
  • Using external properties in Camel routes
  • Reusing endpoints
  • Reusing routing logic through template routes
  • Controlling route startup and shutdown

Introduction

This chapter will introduce you to the fundamentals of running Apache Camel inside your applications. You will learn how to make use of Camel's rich set of components, and how to structure routes in such a way that common integration logic is able to be reused without duplication. These topics will provide you with the foundation for developing integrations using the framework.

Tip

Downloading the example code

Complete examples for each of the code snippets are located at http://github.com/CamelCookbook/camel-cookbook-examples, and through your account on the Packt Publishing's website at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

To try these examples for yourself, obtain the example code, and build it using Apache Maven 3.0 or newer (http://maven.apache.org). Use the following command from the top-level directory of the project. Complete instructions are also provided in the included README file.

# mvn clean install

The code for this chapter is contained within the camel-cookbook-structuring-routes module of the examples.

Using Camel in a Java application

Camel is a framework that is composed of a set of JARs, much as any other library that lives alongside your code. If you wanted to run Camel from the command line, you would define the libraries used within as a list of JARs to be considered by the java and javac command-line tools.

Note

The supporting code for this book uses Camel within the context of Maven projects that build standalone JARs. The JARs are not meant to be executed themselves, rather the Maven project structure is used as a convenient harness for driving JUnit tests that demonstrate the behavior being described.

The Camel libraries are broken up into two categories:

  • Core set of artifacts containing the runtime, test support classes, and build tools.
  • Optional libraries that abstract away the details of dealing with a given technology (for example, messaging via JMS or SOAP services via CXF). At the time of writing, Camel integrates with over 140 technologies (http://camel.apache.org/components.html), and each is encapsulated within its own library with its own dependencies.

This recipe will show you the basic steps to start and stop Camel routes from within your Java application.

Getting ready

The minimal set of libraries typically required to use Camel within a Maven build are:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-core</artifactId>
  <version>${camel-version}</version>
</dependency>
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-test</artifactId>
  <version>${camel-version}</version>
  <scope>test</scope>
</dependency>

The Camel version is usually defined in a properties block within the Maven POM file once, as follows, so as to not need to be repeated over and over:

<properties>
  <camel-version>2.12.2</camel-version>
</properties>

Note

A note on versions

Camel is a very mature framework that can be considered as being "core-complete". It has become the core library for integration in a number of commercial ESBs, and at this stage the underlying architecture is very stable and unlikely to be radically changed.

This book has been written against what will most certainly be an outdated version by the time you read this. Any changes made to Camel since the time of writing are likely to have been additive. There will be more components, and more options around the various integration patterns as further use cases require them. For the very latest detailed documentation, refer to the Camel website.

The Java code for this recipe is located in the org.camelcookbook.structuringroutes.simple package.

How to do it...

  1. Define a route using the Camel Java DSL, by extending the org.apache.camel.builder.RouteBuilder abstract class:
    public class LogMessageOnTimerEventRouteBuilder
        extends RouteBuilder {
      @Override
      public void configure() throws Exception {
        from("timer:logMessageTimer?period=1s")
          .log("Event triggered by ${property.CamelTimerName}"
             + " at ${header.CamelTimerFiredTime}");
      }
    };
  2. The following steps occur in your application's main method. See SimpleCamelApplication from this example. Create a CamelContext implementation:
    CamelContext context = new DefaultCamelContext();
  3. Add the route definition to the context; this can be invoked as many times as you have routes:
    context.addRoutes(
        new LogMessageOnTimerEventRouteBuilder());
  4. Start the context. This loads the route definitions that you have added, and processes messages through them in the background:
    context.start();

    Note

    The CamelContext.start method is non-blocking. It will start up associated Components on internal threads, and return to the caller.

  5. When the Camel application is ready to be shut down, call:
    context.stop();

How it works...

The CamelContext interface is the heart of the Camel framework. It is responsible for processing messages along routes.

The from(...) statement at the start of a route defines an endpoint, or a technology-specific location, that the Camel routing engine uses to fetch messages. Endpoints are defined using URIs, such as in the preceding example, timer:logMessageTimer. The first part of the URI specifies the component that is being used to consume the message, and the remaining is a set of instructions for that specific component. See the Using Camel components recipe in this chapter for more details.

The Camel routing engine consumes exchanges from these endpoints and processes them sequentially through each of the steps defined in the route. The engine is responsible for threading, transactions, error handling, copying messages where required, and many other details.

The Camel context is a long-running object; it is intended to live for as long as the application does, and therefore its initialization and shutdown is usually tied to the lifecycle of the application. Typical deployments of Camel define the context within:

  • The main() method of a standalone command-line application; here it waits indefinitely until the user terminates the process
  • As an instance variable within a javax.servlet.ServletContextListener in a web app, starting up and shutting down along with the application
  • An object tied to an OSGi bundle's lifecycle
  • An object within a Spring or OSGi Blueprint context that is itself tied to the application's lifecycle

Routes, which are definitions of the steps that messages should be processed through, are typically added to the newly created context, though they can be added, removed, and modified at runtime. Route definitions can only be added to a context before the context is started, though they can be stopped and restarted while the context is running.

Extending the RouteBuilder abstract class gives access to Camel's Java route definition DSL, or simply the Java DSL. What this means in practice is that within the mandatory configure() method, after typing the first from(...) statement that defines the start of a route, you get context-specific code completion of whichever integration patterns you might be using.

A RouteBuilder implementation may implement one or many routes. That is, within the configure() method, you can specify multiple from(...) statement that Camel will translate into multiple runtime route instances, one per from(...) statement.

There's more...

Camel is a highly configurable framework, in which most behaviors can be customized through service provider interfaces (SPIs). An SPI encapsulates a single behavior, such as a route naming strategy (Camel gives your routes sensible names if you do not do so explicitly). To override the default behavior, you provide your own implementation of the SPI class and set it on the CamelContext object. The context allows you to define the following, amongst others:

  • Listeners that are notified of Camel lifecycle events
  • Naming strategies for routes, route nodes, and JMX
  • Strategies for shutting down the application gracefully
  • Mechanisms for managing thread pools

It is therefore worthwhile getting familiar with the options that this class gives you by going over the Javadocs.

The CamelContext interface makes use of an internal object registry that allows it to look up objects by name. When using a DefaultCamelContext, a JNDI-aware registry is used.

This feature is used extensively throughout the framework for finding components, thread pools, named processor beans, data formats, and the like.

Occasionally, it is necessary to add objects directly to the registry, as in the case of beans that you want to execute, as one of the processing steps in a route. To do this, instantiate an implementation of org.apache.camel.spi.Repository, usually org.apache.camel.impl.SimpleRegistry, and pass it into the constructor of the DefaultCamelContext:

SimpleRegistry registry = new SimpleRegistry();
registry.put("payloadTransformer", new MyPayloadTransformer());
CamelContext context = new DefaultCamelContext(registry);

The CamelContext interface defines type-safe utility methods for setting certain object types, such as components, that allow you to set them without worrying about the registry internals.

Consider the following manual step:

registry.put("mylogger", new LogComponent());

This can be written in a type-safe way as follows:

context.addComponent("mylogger", new LogComponent());

The Registry in Camel can hold any named Java instance, and these instances can be referenced by name from the Camel DSL. The addComponent method of the CamelContext is specifically used for registering Camel components by name. Both approaches do effectively the same thing, though there are some subtle differences, and we would recommend using the addComponent method for components, and adding all your POJOs and custom processors into the registry.

Embedding Camel in a Spring application

This recipe will show you how to integrate Camel into a Spring application.

Getting ready

When using Camel within a Spring application, it is necessary to add the following dependencies to the minimal set defined in the Using Camel in a Java application recipe in this chapter:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-spring</artifactId>
  <version>${camel-version}</version>
</dependency>
<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-test-spring</artifactId>
  <version>${camel-version}</version>
  <scope>test</scope>
</dependency>

The ${camel-version} property is defined once in the Maven POM.

The Java code for this recipe is located in the org.camelcookbook.structuringroutes.simplespring package. The Spring XML files are located under src/main/resources/META-INF/spring and prefixed with simplespring.

How to do it...

In order to embed Camel into a Spring application, perform the following steps:

  1. In the XML namespace declaration, define the Camel schema alongside any Spring schemas in use:
    <beans
      xmlns="http://www.springframework.org/schema/beans"
      xmlns:camel="http://camel.apache.org/schema/spring"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://camel.apache.org/schema/spring
        http://camel.apache.org/schema/spring/camel-spring.xsd">
  2. The camelContext element should be defined once within the Spring configuration, and it should use the Camel Spring namespace. This signifies that everything within it will be considered Camel configuration as opposed to Spring.
    <camelContext
        xmlns="http://camel.apache.org/schema/spring">
      <!-- routing logic goes here -->
    </camelContext>
  3. Routes can then be defined within the camelContext element using the XML DSL:
    <route>
      <from uri="timer:logMessageTimer?period=1s"/>
      <to uri="mylogger:insideTheRoute?showHeaders=true"/>
      <log
          message="Event triggered by ${property.CamelTimerName} at ${header.CamelTimerFiredTime}"/>
    </route>

How it works...

Camel was designed to be closely integrated with Spring from its inception. The camelContext element results in a SpringCamelContext object being created, initialized with any routes defined within it, and started when the Spring context starts up. The camelContext element is itself a Spring managed object that can optionally be given an ID and treated like any other bean.

The preceding example shows Camel's XML DSL being used. One of the nice things about the DSL is that an XML schema is used to define it. This means that it is possible for your IDE to provide you with code completion.

How it works...

It is not mandatory to use the XML DSL with Spring. It is possible to use the Java DSL instead, or alongside routes defined through the XML DSL.

To plug in the route defined in the LogMessageOnTimerEventRouteBuilder class that we used in the previous recipe, we first instantiate it as a bean:

<!-- package name has been abbreviated -->
<bean id="logMessageOnTimerEvent"
      class="org.camelcookbook.structuringroutes.simple.LogMessageOnTimerEventRouteBuilder"/>

Then we add it to the camelContext element using the routeBuilder tag:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <routeBuilder ref="logMessageOnTimerEvent"/>
</camelContext>

Multiple routeBuilder elements can be used within a camelContext.

There's more...

If you define a number of RouteBuilders in the same package, it is possible for Camel to scan that package and instantiate all of the routes that it finds:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <packageScan>
    <package>org.camelcookbook.structuringroutes</package>
  </packageScan>
</camelContext>

You can add multiple package elements within the packageScan element, and also use wildcards to include or exclude RouteBuilders by name, using the excludes and includes elements.

Spring provides an alternative feature called component scanning. When enabled, the Spring application context recursively scans a package, and instantiates any class within that is annotated with org.springframework.stereotype.Component. Any properties annotated with @Autowired, or the CDI equivalent @Inject, have their dependencies injected. Camel can be configured to pick up any RouteBuilders wired through this process. The RouteBuilders must first be marked as components:

@Component
public class LogMessageOnTimerEventRouteBuilder
    extends RouteBuilder {
  //...
};

To enable the wiring, turn on component scanning in Spring:

<component-scan
  base-package="org.camelcookbook.structuringroutes"
  xmlns="http://www.springframework.org/schema/context"/>

Then add the appropriate feature to the Camel context to tie it all together:

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <component-scan/>
</camelContext>

Using Camel components

When writing integration code, you will inevitably have to work directly with libraries that deal with the technology being integrated. The details of invoking web services, consuming or sending files to FTP servers, or messaging over JMS often take up a substantial proportion of development time on a project. Camel abstracts away the repeated details of consuming from or producing to these "transports", by encapsulating this interaction within a Component.

Camel provides a rich set of components, which abstract away this plumbing code from you. These allow you to focus your energies on the business logic of your integration without worrying about the finer details of the transport.

This recipe will show you the basic steps of associating a Camel Component for a given technology with your integration routing logic.

Getting ready

To make use of a component, you will need to make sure that the component's library is included in your project. The camel-core library provides a set of fundamental components to get you started underneath the org.apache.camel.component package.

For integration with any other technologies, your first stop should be the component listing on the Camel website (http://camel.apache.org/components.html). Once you have found the technology that you are looking for, add the JAR dependency to your project, ensuring that the version matches that of the camel-core library you are using. For example, to use the Camel FTP component within your Camel route, you need to add the camel-ftp dependency to your POM:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-ftp</artifactId>
  <version>${camel-version}</version>
</dependency>

The ${camel-version} property is defined once in the Maven POM.

The Java code for this recipe is located in the org.camelcookbook.structuringroutes.simple package. The Spring XML files are located under src/main/resources/META-INF/spring and prefixed with simplespring.

How to do it...

In order to use a Camel component you need to instantiate and register the component, and then reference it from your Camel route as per the following steps:

  1. If working within a Spring application, you use a Component by instantiating it as a bean and give it a meaningful name (id); the Component is automatically visible to Camel:
    <bean id="mylogger"
          class="org.apache.camel.component.LogComponent"/>

    Alternatively, in a non-Spring Java application, you register a Component by instantiating it and then adding it to the CamelContext before starting it:

    CamelContext context = new DefaultCamelContext();
    camelContext.addComponent("mylogger", new LogComponent());
    // add routes here
    context.start();
  2. To use the component as an endpoint in a to(...) or from(...) statement, refer to the name that you assigned it within the scheme part of the endpoint URI:
    .to("mylogger:insideTheRoute?showHeaders=true")

How it works...

To understand exactly what happens when we use an endpoint URI, it is easiest to take a brief look under the covers at the classes that Camel uses within its component framework.

How it works...

A Component is a factory for creating Endpoints that can act as message Consumers, or Producers, or both. An implementation will typically have bean properties on it that will apply to the transport as a whole. For example, the JMS Component requires that a ConnectionFactory be set on it, in order to make use of the same message broker for all JMS communication:

<bean id="myFavouriteMQ"
      class="org.apache.camel.component.jms.JmsComponent">
  <property name="connectionFactory"
            ref="myConnectionFactory"/>
</bean>

All Components implement a method used to parse the endpoint URI:

Endpoint createEndpoint(String uri) throws Exception;

An Endpoint can be thought of as an address that is specific to the component technology–it is instantiated from the URI by the framework when the route using it is started. The scheme portion of the URI, the part before the first colon (:), identifies the component implementation being used.

Continuing the JMS example, given that the Component already knows where a message broker is, the Endpoint itself describes which queues or topics a message should be sent to or received from, and how:

myFavouriteMQ:someQueue?concurrentConsumers=5

The portion of the URI after the scheme is specific to the endpoint technology. The URI properties themselves, such as concurrentConsumers, correspond to bean properties on the endpoint implementation for that technology, and are set using introspection. If you were to take a look inside the JMS Component library, you would see a JmsEndpoint object with a setConcurrentConsumers(int consumers) method.

You should always refer back to the applicable Camel component page for a full list of properties that can be used.

The Endpoint is also a factory. Camel uses it for creating Producers and Consumers, depending on the context of where the URI is used. The following factory methods are defined on the interface:

Producer createProducer() throws Exception;
Consumer createConsumer(Processor processor) throws Exception;

These classes handle the heavy lifting of talking to the underlying technology.

If the endpoint URI is used in a from(...) statement, Camel will create a Consumer. If it is used in a to(...) block, will create a Producer.

There's more...

The same component can be instantiated multiple times with different IDs. For example, two JMS components might be used when writing routing logic to bridge message brokers from different vendors.

See also

Reusing routing logic by connecting routes

It is frequently necessary to execute the same processing steps within multiple routes. Camel provides you with a mechanism to call routing steps in a shared route. You can then reuse that route in a similar fashion to a method in a regular Java program.

This recipe will show you a strategy for developing your routes so that common routing tasks can be defined within a shared route called from other routes.

Getting ready

Determine the routing logic that you would like to reuse, and move it to a route that consumes from a direct: URI.

The Java code for this recipe is located in the org.camelcookbook.structuringroutes.direct package. The Spring XML files are located under src/main/resources/META-INF/spring and prefixed with direct.

How to do it...

Create a route with the from URI using the direct: endpoint, and then in another route, call the shared route using the same direct: endpoint.

  1. The direct: endpoint name, which is an arbitrary alphanumeric string, follows the colon in the URI, must be unique within the containing Camel context:

    In the XML DSL, it is used as follows:

    <route>
      <from uri="direct:prefixBodyWithHello"/>
      <transform>
        <simple>Hello, ${body}</simple>
      </transform>
      <log message="Prefixed message: ${body}"/>
    </route>

    In the Java DSL, the same thing is expressed as:

    from("direct:prefixBodyWithHello")
      .transform(simple("Hello, ${body}"))
      .log("Prefixed message: ${body}");
  2. Invoke the shared route from within the top-level route that needs to make use of this logic by using the same direct: URI:

    In the XML DSL, this is written as follows:

    <route>
      <from uri="..."/>
      <to uri="direct:prefixBodyWithHello"/>
    </route>

    In the Java DSL, this appears as:

    from(...).to("direct:prefixBodyWithHello");

How it works...

Each direct: endpoint may only be consumed (used within the from(...) block) by one route in a Camel context. However, multiple routes may produce, or send, messages to that URI. This allows you to compose your routing logic in easily understandable blocks, much as you would when using methods in a regular Java program.

The shared route can be considered as a part of the top-level route. It operates on the same Exchange object, and participates in any transactions that the top-level route has initiated.

Regardless of whether the message exchange pattern on the exchange is InOnly or InOut, the behavior of invoking a direct: endpoint is the same; that is, the exchange will flow through all of the processing steps defined in the shared route and will be returned to the calling route on completion where it will proceed to the next processing step.

There's more...

It is possible to invoke the shared route, and merge the returned exchange with the exchange containing the original state before the route was invoked. See the Enriching your content with some help from other endpoints recipe in Chapter 4, Transformation, for more details.

See also

Asynchronously connecting routes

It is not uncommon to have a portion of route take a long time to process. Rather than tying up a thread that might otherwise be servicing requests from a consumer endpoint, it may be preferable to split out the time consuming step into a separate route, and let that stage of processing be handled by a dedicated pool of threads.

This recipe will show you how to call a route from another, such that the calling route does not block waiting for the response from the called route.

Getting ready

Split out the long running steps into their own shared routes, and assign them with a seda: endpoint with a name that is unique to the Camel context.

The Java code for this recipe is located in the org.camelcookbook.structuringroutes.seda package. The Spring XML files are located under src/main/resources/META-INF/spring and prefixed with seda.

How to do it...

Create a shared route using the seda: endpoint, and then call it from other routes using the same named seda: endpoint.

  1. Create a route consuming (from) using a seda: endpoint. Optionally, define the number of threads that will consume from this endpoint using the concurrentConsumers attribute.

    In the XML DSL, this is written as:

    <route>
      <from
        uri="seda:longRunningPhase?concurrentConsumers=15"/>
      <process ref="longRunningProcessor"/>
      <to uri="..."/>
    </route>

    In the Java DSL, the same thing appears as:

    from("seda:longRunningPhase?concurrentConsumers=15")
      .process(new LongRunningProcessor())
      .to(...); // remainder of route
  2. In the calling route, pass the current exchange to the shared route by invoking the seda: endpoint by name.

    In the XML DSL, this is done as follows:

    <route>
      <from uri="timer:ping?period=200"/>
      <to uri="seda:longRunningPhase"/>
    </route>

    In the Java DSL, this same thing is written as:

    from("timer:ping?period=200")
      .to("seda:longRunningPhase");

How it works...

In the preceding example, a timer: endpoint is used to trigger messages on a regular basis, every 200 ms. The Timer Component uses one thread per timer name (ping). An event can only be raised 200 ms later if the thread is not processing the previous exchange.

As part of our integration, we want to trigger events regularly, and yet have a long-running processor as part of the route. Camel allows us to deal with this scenario by splitting the long-running part into a shared route, and linking the two routes with a seda: endpoint.

Note

SEDA is an acronym that stands for Staged Event-Driven Architecture. It is designed as a mechanism to regulate the flow between different phases of message processing. The idea is to smooth out the frequency of message output from an overall process so that it matches the input.

In practical terms, it allows an endpoint's consumer threads to offload the work of long-running operations into the background, thereby freeing them up to consume messages from the transport.

When an exchange is passed to a seda: endpoint, it is placed into a BlockingQueue. The list exists within the Camel context, which means that only those routes that are within the same context can be joined by this type of endpoint. The queue is unbounded by default, although that can be changed by setting the size attribute on the URI of the consumer.

By default, a single thread assigned to the endpoint reads exchanges off the list and processes them through the route. As seen in the preceding example, it is possible to increase the number of concurrentConsumers to ensure that exchanges are getting processed from that list in a timely fashion.

Assuming our slow processor takes 3,000 ms to complete, we would need to use a number of threads equal to the processing time/the timer frequency to ensure that the triggered events are processed in a timely fashion. Therefore, plugging in the numbers, 3,000 ms / 200 ms, we arrive at 15 threads.

There's more...

It is possible to define multiple routes that consume from the same logical name, unlike a direct: endpoint. To enable this, both routes should set multipleConsumers=true on the seda: URI:

from("seda:timerEvents?multipleConsumers=true")
  // define one set of routing logic here

from("seda:timerEvents?multipleConsumers=true")
  // another here

The effect will be that each route gets its own copy of the exchange, making it a sort of simple in-memory publish-subscribe system. It is often much cleaner to handle this type of requirement using the Multicast pattern. See the Multicast – routing the same message to many endpoints recipe in Chapter 2, Message Routing, for more details.

The SEDA pattern is best suited to processing the InOnly messages, where one route finishes processing and hands off to another to deal with the next phase. It is possible to ask for a response from a seda: endpoint by calling it when the message exchange pattern is InOut.

In this instance, the endpoint will act much like a synchronous direct: endpoint, only with a timeout if the task runs for longer than expected. The default timeout is 30 seconds, but this can be overridden in the producer URI using the timeout attribute.

Note

It is important to note that when using seda:, the shared route does not take part in any transactions started by the top-level route, as transactions are bound to a thread and the seda: route is using its own thread. If the system unexpectedly halts for whatever reason (for example, a power outage), any messages that are being processed within that route will be lost.

If you would like to get the benefits of a SEDA, but have the messages persisted to disk instead of in-memory, and be processed within a transaction, use the JMS or ActiveMQ endpoints with a message broker instead. This also gives you the ability to share the work across Camel contexts and JVMs.

See also

To trigger a background job to run based on the current exchange while your main route continues processing, refer to the Wire Tap EIP. See Wire Tap sending a copy of the message elsewhere recipe in Chapter 2, Message Routing, for more details.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A practical guide to using Apache Camel delivered in dozens of small, useful recipes.
  • Written in a Cookbook format that allows you to quickly look up the features you need, delivering the most important steps to perform with a brief follow-on explanation of what's happening under the covers.
  • The recipes cover the full range of Apache Camel usage from creating initial integrations, transformations and routing, debugging, monitoring, security, and more.

Description

Apache Camel is a de-facto standard for developing integrations in Java, and is based on well-understood Enterprise Integration Patterns. It is used within many commercial and open source integration products. Camel makes common integration tasks easy while still providing the developer with the means to customize the framework when the situation demands it. Tasks such as protocol mediation, message routing and transformation, and auditing are common usages of Camel. Apache Camel Developer's Cookbook provides hundreds of best practice tips for using Apache Camel in a format that helps you build your Camel projects. Each tip or recipe provides you with the most important steps to perform along with a summary of how it works, with references to further reading if you need more information. This book is intended to be a reliable information source that is quicker to use than an Internet search. Apache Camel Developer's Cookbook is a quick lookup guide that can also be read from cover to cover if you want to get a sense of the full power of Apache Camel. This book provides coverage of the full lifecycle of creating Apache Camel-based integration projects, including the structure of your Camel code and using the most common Enterprise Integration patterns. Patterns like Split/Join and Aggregation are covered in depth in this book. Throughout this book, you will be learning steps to transform your data. You will also learn how to perform unit and integration testing of your code using Camel's extensive testing framework, and also strategies for debugging and monitoring your code. Advanced topics like Error Handling, Parallel Processing, Transactions, and Security will also be covered in this book. This book provides you with practical tips on using Apache Camel based on years of hands-on experience from hundreds of integration projects.

Who is this book for?

Apache Camel Developer's Cookbook is intended for developers who have some familiarity with Apache Camel and who want a quick lookup reference to practical, proven tips on how to perform common tasks. Every recipe also includes a summary and reference pointers for more details that make it easy for you to get a deeper understanding of the Apache Camel capabilities that you will use day to day.

What you will learn

  • Learn ways to structure your Camel projectsUnderstand common Enterprise Integration Pattern usageTransform your messagesUse Camel s built-in testing frameworkExtend Camel to better interoperate with your existing codeLearn the strategies for Error HandlingUse Camel s parallel processing and threading capabilitiesSecure your Camel integration routesUnderstand ACID Transaction processing within Camel

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 26, 2013
Length: 424 pages
Edition : 1st
Language : English
ISBN-13 : 9781782170303
Vendor :
Apache
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 26, 2013
Length: 424 pages
Edition : 1st
Language : English
ISBN-13 : 9781782170303
Vendor :
Apache
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
R$500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
R$800 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 608.97
Apache Camel Developer's Cookbook
R$306.99
Instant Apache Camel Message Routing
R$150.99
Instant Apache Camel Messaging System
R$150.99
Total R$ 608.97 Stars icon

Table of Contents

13 Chapters
1. Structuring Routes Chevron down icon Chevron up icon
2. Message Routing Chevron down icon Chevron up icon
3. Routing to Your Code Chevron down icon Chevron up icon
4. Transformation Chevron down icon Chevron up icon
5. Splitting and Aggregating Chevron down icon Chevron up icon
6. Parallel Processing Chevron down icon Chevron up icon
7. Error Handling and Compensation Chevron down icon Chevron up icon
8. Transactions and Idempotency Chevron down icon Chevron up icon
9. Testing Chevron down icon Chevron up icon
10. Monitoring and Debugging Chevron down icon Chevron up icon
11. Security Chevron down icon Chevron up icon
12. Web Services Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(17 Ratings)
5 star 52.9%
4 star 23.5%
3 star 11.8%
2 star 5.9%
1 star 5.9%
Filter icon Filter
Top Reviews

Filter reviews by




Ravindra Godbole Aug 03, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very useful book for Apache Camel users for practical usage of framework. It provides live examples in Java as well as Spring DSL and list many best practices while authoring routes. A collection of complex routes deployed in various scenarios in the enterprises which are currently using Apache Camel will be great help to readers of the book [ apart from the per topic examples provided ]
Amazon Verified review Amazon
Brennan Apr 27, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Exactly what I was looking for to bootstrap a Camel+AMQ deployment. Easy to find what you're looking for, and shows both regular Java DSL's and Spring integrations.
Amazon Verified review Amazon
SuJo Sep 15, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Wow! What an amazing book to get started with Apache Camel, I've never used this before and found this book immensely helpful. It was a practical read, very organized, and covered everything I expected to learn. The parallel processing was probably my favorite chapter, with error handling in a close 2nd place. The book was easily understood and well worth the $25, which if you catch a sale or one of the specials makes buying more than one book advantageous.Debugging and Security were on point and I'm always critical about these two areas, you need to find bugs and squash them along with maintaining the integrity of the application even on the security side. Overall I felt the book delivered and was not overdone, just enough to get me started while leaving room for growth which I would get into more advanced books for.Publisher Link: https://www.packtpub.com/application-development/apache-camel-developers-cookbook
Amazon Verified review Amazon
Thomas Walzer Jun 11, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
tl;dr: buy nowThis book is essential reading for every serious Apache Camel developer. Its return on investment is great even if you only use a single recipe. But you will be able to use many of them. It greatly reduces the learning curve (and head scratching) and you will find a lot of material not covered anywhere else.This book will not gather dust on a shelf (or in the Amazon cloud), you will use it often.
Amazon Verified review Amazon
Christian Posta Jan 07, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Apache Camel is the de-facto standard java integration library with support for hundreds of components for talking to external systems, implementation of the enterprise integration patterns from the EIP book, all wrapped up in a declarative, expressive DSL. Throw in testing support out of the box, vibrant community, and production support, and you cannot beat it for integration work.Camel in Action is the authoritative book up to this point on understanding and using Apache Camel. This book builds on that foundational knowledge and demonstrates, step-by-step, how to use Camel to solve real world problems. The content is divided into small bite-sized chunks of functionality or recipes that explain how to solve a specific problem in both the XML and Java DSL as well as how it works and things to watch out for.If you just recently learned Camel and are looking for best practices for solving common integration problems, I highly recommend it. It's targeted toward a moderate to advanced leaning set of architects and developers who already have some experience with Camel.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.