Thursday, 17 October 2013

Camel ProducerTemplate and ConsumerTemplate Example


The ProducerTemplate interface allows you to send message exchanges to endpoints in a variety of different ways to make it easy to work with Camel endpoint instances from Java code. See more about templates . ConsumerTemplate is for working with Camel and consuming message instances in an Exchange from an Endpoint. See more


Here is one Camel routing example which is using  Producer and Consumer templates to send and receive messages. In this example Apache activemq is using for messaging services.

1. Start Activemq Message broker.

In order to send and receive messages we have to start Apache activemq message broker before running this main program.

2. Create a Maven Project.

Create a maven project and add below dependencies


2. Create Spring configuration file (camel-context.xml)

In this Spring configuration file we are defining camel templates inside context. Also adding bean definition for activemq component.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Configures the Camel Context-->
<beans xmlns=""

<!-- Definfing producer and consumer templates -->
 <camel:camelContext id="camel-client">
    <camel:template id="camelTemplate" />
    <camel:consumerTemplate id="camelConsumer" />
  <!-- Definfing ActiveMQComponent and properties -->
 <bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent">
        <property name="brokerURL" value="tcp://localhost:61616" />

3. Create a Main class ( 

In this main class we will load all the components which we defined in the configuration file and create templates to send and receive messages.

import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.springframework.context.ApplicationContext;
public class TemplateTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
        ProducerTemplate pTemplate = context.getBean("camelTemplate",
        System.out.println("Message Sending started");
                "Hello welcome to camel templates");
        System.out.println("Message sent");
        ConsumerTemplate cTemplate = context.getBean("camelConsumer",
        System.out.println("Message Consuming started");
        Exchange ex = cTemplate.receive("jms:queue:testQSource");
        System.out.println("Message received:" + ex.getIn().getBody());

3. Run the program

Upon running this main program we can see below logs are in the console and Queue details in the ActiveMQ console (http://localhost:8161/admin/)

Message Sending started
Message sent
Message Consuming started
Message received:Hello welcome to camel templates


Reference: Apache Camel