[CONF] Apache Camel: Tutorial-JmsRemoting (page edited)

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

[CONF] Apache Camel: Tutorial-JmsRemoting (page edited)

Dhiraj Bokde (Confluence)

Tutorial-JmsRemoting has been edited by Claus Ibsen (Jun 09, 2008).

(View changes)

This tutorial is a work in progress. Any additions, corrections or feedback very much appreciated. Please use the comment box if making a correction explaining the mistake.


This tutorial aims to guide the reader through the stages of creating a project which uses Camel to facilitate the routing of messages from a JMS queue to a Spring service. The route works in a synchronous fashion returning a response to the client.


  • Embellish the tutorial with more detail, explaining at each stage what is happening.
  • Link to specific sections of Camel documentation when referring to components.
  • Attach completed example project.
  • Explain in more detail what is happening when the JMS component is being defined in camel-server.xml
  • Show how logging can be introduced to monitor exchange body contents.
  • Detail how time-outs can be configured.
  • Show how to catch lost messages.
  • Show how to use a wiretap.
  • Can we make this ActiveMQ embedded so that it does not require the reader to download and start it manually?


This tutorial uses Maven to setup the Camel project and for dependencies for artifacts.

Create the Camel Project

For the purposes of the tutorial a single Maven project will be used for both the client and server. Ideally you would break your application down into the appropriate components.

mvn archetype:create -DgroupId=org.example -DartifactId=CamelWithJmsAndSpring

Update the POM with Dependencies

First we need to have dependencies for the core Camel jars and its spring and jms components.

<!-- required by both client and server -->

As we use spring xml configuration for the ActiveMQ JMS broker we need this dependency:

<!-- xbean is required for ActiveMQ broker configuration in the spring xml file -->

And dependencies for the AOP enable server example:

<!-- required jars for aspectj AOP support -->

Writing the Server

Create the Spring Service

For this example the Spring service (= our business service) on the server will be a simple multiplier which trebles in the received value.

public interface Multiplier {

     * Multiplies the given number by a pre-defined constant.
     * @param originalNumber The number to be multiplied
     * @return The result of the multiplication
    int multiply(int originalNumber);


And the implementation of this service is:

@Service(value = "multiplier")
public class Treble implements Multiplier {

    public int multiply(final int originalNumber) {
        return originalNumber * 3;


Notice that this class has been annotated with the @Service spring annotation. This ensures that this class is registered as a bean in the registry with the given name multiplier.

Define the Camel Routes

public class ServerRoutes extends RouteBuilder {

    public void configure() throws Exception {
        // invoke the bean with the id multiplier, and its multiply method
        from("jms:queue:numbers").beanRef("multiplier", "multiply");


This defines a Camel route from the JMS queue named numbers to the Spring bean named multiplier. Camel will create a consumer to the JMS queue which forwards all received messages onto the the Spring bean, using the method named multiply.

Configure Spring

The Spring config file is placed under META-INF/spring as this is the default location used by the Camel Maven Plugin, which we will later use to run our server.
First we need to do the standard scheme declarations in the top. In the camel-server.xml we are using spring beans as the default namespace and springs context:. For configuring ActiveMQ we use broker: and for Camel we of course have :camel.

<beans xmlns="http://www.springframework.org/schema/beans"
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
		http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring-1.3.0.xsd
		http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.1.0.xsd">

We use Spring annotations for doing IoC dependencies and its component-scan features comes to the resource as it scans for spring annotations in the given package name:

<!-- let Spring do its IoC stuff in this package -->
<context:component-scan base-package="org.apache.camel.example.server"/>

Camel will of course not be less than Spring in this regard so it supports a similar feature for scanning of Routes. This is configured as shown below:

<!-- declare a camel context that scans for classes that is RouteBuilder
     in the package org.apache.camel.example.server -->
<camel:camelContext id="camel">

The ActiveMQ JMS broker is configured in this xml file. We set it up to listen on TCP port 61616.

<!-- lets configure the ActiveMQ JMS broker server to listen on TCP 61616 -->
<broker:broker useJmx="false" persistent="false" brokerName="localhost">
        <broker:transportConnector name="tcp" uri="tcp://localhost:61616"/>

As this examples uses JMS then Camel needs a JMS component that is connected with the ActiveMQ broker. This is configured as shown below:

<!-- lets configure the Camel JMS consumer to use the ActiveMQ broker declared above -->
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
    <property name="connectionFactory">
        <bean class="org.apache.activemq.ActiveMQConnectionFactory">
            <!-- use the vm protocol as the JMS broker is running in the same jvm as Camel -->
            <property name="brokerURL" value="vm://localhost"/>

Notice: The JMS component is configured in standard Spring beans, but the gem is that the bean id can be reference in Camel routes so we can do routing with the jms: prefix in the URIs and Camel will find this bean in the Registry and use this JMS Component. If you don't like jms you can name the bean id as you like (eg activemq, myjmsbroker, messaging etc). We use the vm protocol to connect to the ActiveMQ server as its embedded in this application.

component-scan Defines the package to be scanned for Spring stereotype annotations, in this case, to load the "multiplier" bean
camel-context Defines the package to be scanned for Camel routes. Will find the ServerRoutes class and create the routes contained within it
jms bean Creates the Camel JMS component

AOP Enabled Server

The example has an enhanced Server example that uses fullblown Aspejct AOP for doing a audit tracking of invocations of the business service.

We leverage Spring AOP support in the {{camel-server-aop.xml} configuration file. First we must declare the correct XML schemas to use:

<beans xmlns="http://www.springframework.org/schema/beans"
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
		http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring-1.3.0.xsd">

Then we include all the existing configuration from the normal server example:

<!-- import the normal server that is the JMS broker -->
<import resource="camel-server.xml"/>

Then we enable the AspejctJ AOP auto proxy feature of Spring that will scan for classes annotated with the @Aspect annotation:

<!-- turn on AspejctJ AOP to weave all @Aspects beans declared in this spring xml file -->

Then we define our Audit tracker bean that does the actual audit logging. It's also the class that is annotated with the @Aspect so Spring will pick this up, as the aspect.

<!-- Aspect that tracks all the invocations of the business service -->
<bean id="AuditTracker" class="org.apache.camel.example.server.AuditTracker">
    <!-- define what store to use for audit backup -->
    <property name="store" ref="AuditStore"/>

And the gem is that we inject the AuditTracker aspect bean with a Camel endpoint that defines where the audit should be stored. Noticed how easy it is to setup as we have just defined an endpoint URI that is file based, meaning that we stored the audit tracks as files. We can change this tore to any Camel component as we wish. To store it on a JMS queue simply change the URI to jms:queue:audit.

<!-- the audit store endpoint is configued as file based -->
<camel:endpoint id="AuditStore" uri="file://target/store?append=false"/>

And the full blown Aspejct for the audit tracker java code:

 * For audit tracking of all incoming invocations of our business (Multiplier)
public class AuditTracker {

    // endpoint we use for backup store of audit tracks
    private Endpoint store;

    public void setStore(Endpoint store) {
        this.store = store;

    @Before("execution(* org.apache.camel.example.server.Multiplier.*(..)) && args(originalNumber)")
    public void audit(int originalNumber) throws Exception {
        String msg = "Someone called us with this number " + originalNumber;

        // now send the message to the backup store using the Camel Message Endpoint pattern
        Exchange exchange = store.createExchange();

Run the Server

The Server is started using the org.apache.camel.spring.Main class that can start camel-spring application out-of-the-box. The Server can be started in several flavors:

  • as a standard java main application - just start the org.apache.camel.spring.Main class
  • using maven jave:exec
  • using camel:run

In this sample as there are two servers (with and without AOP) we have prepared some profiles in maven to start the Server of your choice.
The server is started with:
mvn compile exec:java -PCamelServer

Or for the AOP enabled Server example:
mvn compile exec:java -PCamelServerAOP

Creating the Client

We will initially create a client by directly using ProducerTemplate. We will later create a client which uses Spring remoting to hide the fact that messaging is being used.

<beans xmlns="http://www.springframework.org/schema/beans"
	    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring-1.3.0.xsd">
<camel:camelContext id="camel"/>
<camel:template id="camelTemplate"/>
<!-- Camel JMSProducer to be able to send messages to a remote Active MQ server -->
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
    <property name="connectionFactory">
        <bean class="org.apache.activemq.ActiveMQConnectionFactory">
            <property name="brokerURL" value="tcp://localhost:61616"/>

The client will not use the Camel Maven Plugin so the Spring XML has been placed in src/main/resources to not conflict with the server configs.

camelContext The Camel context is defined but does not contain any routes
template The ProducerTemplate is used to place messages onto the JMS queue
jms bean This initialises the Camel JMS component, allowing us to place messages onto the queue

And the CamelClient source code:

public static void main(final String[] args) throws Exception {
    System.out.println("Notice this client requires that the CamelServer is already running!");

    ApplicationContext context = new ClassPathXmlApplicationContext("camel-client.xml");
    ProducerTemplate camelTemplate = (ProducerTemplate) context.getBean("camelTemplate");

    System.out.println("Invoking the multiply with 22");
    // as opposed to the CamelClientRemoting example we need to define the service URI in this java code 
    int response = (Integer)camelTemplate.sendBody("jms:queue:numbers", ExchangePattern.InOut, 22);
    System.out.println("... the result is: " + response);


The ProducerTemplate is retrieved from a Spring ApplicationContext and used to manually place a message on the "numbers" JMS queue. The exchange pattern (ExchangePattern.InOut) states that the call should be synchronous, and that we will receive a response.

Before running the client be sure that both the ActiveMQ broker and the CamelServer are running.

Using Spring Remoting

Spring Remoting "eases the development of remote-enabled services". It does this by allowing you to invoke remote services through your regular Java interface, masking that a remote service is being called.

<!-- Camel proxy for a given service, in this case the JMS queue -->

The snippet above only illustrates the different and how Camel easily can setup and use Spring Remoting in one line configurations.

The proxy will create a proxy service bean for you to use to make the remote invocations. The serviceInterface property details which Java interface is to be implemented by the proxy. serviceUrl defines where messages sent to this proxy bean will be directed. Here we define the JMS endpoint with the "numbers" queue we used when working with Camel template directly. The value of the id property is the name that will be the given to the bean when it is exposed through the Spring ApplicationContext. We will use this name to retrieve the service in our client. I have named the bean multiplierProxy simply to highlight that it is not the same multiplier bean as is being used by CamelServer. They are in completely independent contexts and have no knowledge of each other. As you are trying to mask the fact that remoting is being used in a real application you would generally not include proxy in the name.

And the Java client source code:

public static void main(final String[] args) {
    System.out.println("Notice this client requires that the CamelServer is already running!");

    ApplicationContext context = new ClassPathXmlApplicationContext("camel-client-remoting.xml");
    // just get the proxy to the service and we as the client can use the "proxy" as it was
    // a local object we are invocing. Camel will under the covers do the remote communication
    // to the remote ActiveMQ server and fetch the response.
    Multiplier multiplier = (Multiplier)context.getBean("multiplierProxy");

    System.out.println("Invoking the multiply with 33");
    int response = multiplier.multiply(33);
    System.out.println("... the result is: " + response);


Again, the client is similar to the original client, but with some important differences.

  1. The Spring context is created with the new camel-client-remoting.xml
  2. We retrieve the proxy bean instead of a ProducerTemplate. In a non-trivial example you would have the bean injected as in the standard Spring manner.
  3. The multiply method is then called directly. In the client we are now working to an interface. There is no mention of Camel or JMS inside our Java code.

Using the Camel Maven Plugin

Require an explanation here about the deployment options of Camel based projects (e.g. running through Maven, creating a host application, deploying into ActiveMQ) and the pros/cons of each.

The Camel Maven Plugin allows you to run your Camel routes directly from Maven. This negates the need to create a host application, as we did with Camel server, simply to start up the container. This can be very useful during development to get Camel routes running quickly.


All that is required is a new plugin definition in your Maven POM. As we have already placed our Camel config in the default location (camel-server.xml has been placed in META-INF/spring/) we do not need to tell the plugin where the route definitions are located. Simply run mvn camel:run.

TODO: Testing

TODO: Detail how to unit and integration test this example.

See Also