Spring AMQP RabbitMQ Example

Filed Under: JMS

Today we will look into Spring AMQP RabbitMQ example application. We have already discussed some “Spring AMQP Basics Theoretically” and “How to install and setup RabbitMQ Server” in my previous posts. Please refer them in the following:

In this post, we are going to develop a Spring AMQP RabbitMQ Messaging application. Let us start it now.

Spring AMQP RabbitMQ Example

Let us start developing a Spring AMQP RabbitMQ Messaging application using Maven, Eclipse IDE and RabbitMQ Server. It is same for all other Java IDEs.

Please do the following the steps one by one:

  1. Create a Maven Java project in Eclipse IDE
  2. Develop Spring AMQP Publisher program
  3. 
    package com.tp.spring.amqp.rabbit;
    
    import org.springframework.amqp.core.AmqpTemplate;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringAMQPRabbitSender {
        private final String SENDER_XML = "springamqp-rabbit-sender-context.xml";
        public static void main(String[] args) throws Exception {
          AmqpTemplate amqpTemplate = (AmqpTemplate)(new ClassPathXmlApplicationContext(SENDER_XML)).getBean("amqpTemplate");
          int messagCount = 0;
    	  while (messagCount < 10){
    	    amqpTemplate.convertAndSend("tp.routingkey.1", "Message # " + messagCount++);
    	  }
    	  System.out.println( messagCount + " message(s) sent successfully.");
    	}
    }
    
  4. Configure Spring AMQP Publisher required beans : springamqp-rabbit-sender-context.xml
  5. 
    <?xml version="1.0"encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	  xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    	  xsi:schemaLocation="http://www.springframework.org/schema/beans 
    	  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    	  http://www.springframework.org/schema/rabbit 
    	  http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
    
    	<rabbit:connection-factory id="connectionFactory" 
    	host="localhost" username="tpuser" password="tpuser"/>
    
    	<rabbit:admin connection-factory="connectionFactory"/>
    	
    	<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
    	exchange="tpExchange"/>	
    </beans>
    
  6. Develop Spring AMQP Consumer(Spring MDP) program
  7. 
    package com.tp.spring.amqp.rabbit;
    
    import org.springframework.amqp.core.Message;
    import org.springframework.amqp.core.MessageListener;
    // Spirng MDP(Message Driven POJO)
    public class SpringAMQPRabbitAyncListener implements MessageListener {
    	@Override
    	public void onMessage(Message message) {
    		System.out.println("Listener received message = " + new String(message.getBody()));
    	}
    }
    
  8. Configure Spring AMQP Consumer required beans : springamqp-rabbt-listener-context.xml
  9. 
    <?xmlversion="1.0"encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    	  xsi:schemaLocation="http://www.springframework.org/schema/beans 
    	  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    	  http://www.springframework.org/schema/rabbit
    	  http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
    
    	<rabbit:connection-factory id="connectionFactory" host="localhost" 
                  username="tpuser" password="tpuser"/>
    
    	<rabbit:admin connection-factory="connectionFactory"/>
    	<rabbit:queue id="tpQueue"/>
    	
    	<rabbit:topic-exchange id="tpExchange" name="tpExchange">
    		<rabbit:bindings>
    			<rabbit:binding queue="tpQueue" pattern="tp.routingkey.1">
    			</rabbit:binding>
    		</rabbit:bindings>
    	</rabbit:topic-exchange>
    	
    	<bean id="asyncListener" class="com.tp.spring.amqp.rabbit.SpringAMQPRabbitAyncListener"/>
    	<rabbit:listener-container id="myListenerContainer" connection-factory="connectionFactory">
    		<rabbit:listener ref="asyncListener" queue-names="tpQueue"/>
    	</rabbit:listener-container>
    
    </beans>
    
  10. Develop Spring AMQP Rabbit Container program to initialize Spring IOC Container
  11. 
    package com.tp.spring.amqp.rabbit;
    
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringAMQPRabbitlListenerContainer {
    	public static void main(String[] args) {
            // Initialize Spring IOC Container
            new ClassPathXmlApplicationContext("springamqp-rabbt-listener-context.xml");
    	}
    }
    
  12. Final pom.xml file
  13. 
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>com.tp</groupId>
    	<artifactId>spring-amqp-rabbitmq</artifactId>
    	<name>spring-amqp-rabbitmq</name>
    	<packaging>jar</packaging>
    	<version>1.0.0</version>
    	<properties>
    		<java-version>1.6</java-version>
    		<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
    		<org.aspectj-version>1.6.10</org.aspectj-version>
    		<org.slf4j-version>1.6.6</org.slf4j-version>
    	</properties>
    	<dependencies>
    		<!-- Spring -->
    		<dependency>
    		  <groupId>org.springframework</groupId>
    		  <artifactId>spring-context</artifactId>
    		  <version>${org.springframework-version}</version>
    		  <exclusions>
    			<!-- Exclude Commons Logging in favor of SLF4j -->
    			<exclusion>
    				<groupId>commons-logging</groupId>
    				<artifactId>commons-logging</artifactId>
    			 </exclusion>
    		  </exclusions>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>${org.springframework-version}</version>
    		</dependency>
    				
    		<!-- AspectJ -->
    		<dependency>
    			<groupId>org.aspectj</groupId>
    			<artifactId>aspectjrt</artifactId>
    			<version>${org.aspectj-version}</version>
    		</dependency>	
    		<!-- Logging -->
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-api</artifactId>
    			<version>${org.slf4j-version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>jcl-over-slf4j</artifactId>
    			<version>${org.slf4j-version}</version>
    			<scope>runtime</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-log4j12</artifactId>
    			<version>${org.slf4j-version}</version>
    			<scope>runtime</scope>
    		</dependency>
    		<dependency>
    			<groupId>log4j</groupId>
    			<artifactId>log4j</artifactId>
    			<version>1.2.15</version>
    			<exclusions>
    				<exclusion>
    					<groupId>javax.mail</groupId>
    					<artifactId>mail</artifactId>
    				</exclusion>
    				<exclusion>
    					<groupId>javax.jms</groupId>
    					<artifactId>jms</artifactId>
    				</exclusion>
    				<exclusion>
    					<groupId>com.sun.jdmk</groupId>
    					<artifactId>jmxtools</artifactId>
    				</exclusion>
    				<exclusion>
    					<groupId>com.sun.jmx</groupId>
    					<artifactId>jmxri</artifactId>
    				</exclusion>
    			</exclusions>
    			<scope>runtime</scope>
    		</dependency>
    
    		<!-- @Inject -->
    		<dependency>
    			<groupId>javax.inject</groupId>
    			<artifactId>javax.inject</artifactId>
    			<version>1</version>
    		</dependency>
    				
    		<!-- Servlet -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>servlet-api</artifactId>
    			<version>2.5</version>
    			<scope>provided</scope>
    		</dependency>
    		<dependency>
    			<groupId>javax.servlet.jsp</groupId>
    			<artifactId>jsp-api</artifactId>
    			<version>2.1</version>
    			<scope>provided</scope>
    		</dependency>
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>jstl</artifactId>
    			<version>1.2</version>
    		</dependency>
    	
    		<!-- Test -->
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>4.7</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.amqp</groupId>
    			<artifactId>spring-rabbit</artifactId>
    			<version>1.1.1.RELEASE</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.amqp</groupId>
    			<artifactId>spring-amqp</artifactId>
    			<version>1.1.4.RELEASE</version>
    		</dependency>
    	</dependencies>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <version>2.9</version>
                    <configuration>
                        <additionalProjectnatures>
                            <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                        </additionalProjectnatures>
                        <additionalBuildcommands>
                            <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                        </additionalBuildcommands>
                        <downloadSources>true</downloadSources>
                        <downloadJavadocs>true</downloadJavadocs>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.5.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <compilerArgument>-Xlint:all</compilerArgument>
                        <showWarnings>true</showWarnings>
                        <showDeprecation>true</showDeprecation>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.2.1</version>
                    <configuration>
                        <mainClass>org.test.int1.Main</mainClass>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    
  14. Our Final Maven Project Structure
  15. spring amqp rabbitmq example

Test Spring AMQP RabbitMQ Example with RabbitMQ Server

  1. Run AMQP Publisher and observe messages in RabbitMQ Queue
  2. spring rabbitmq amqp sender

    Here we can see that AMQP Publisher sent 10 messages successfully.

  3. RabbitMQ console is showing 10 messages in the queue
  4. spring rabbitmq example

    Here we can see that our RabbitMQ queue has received 10 messages successfully from AMQP Publisher.

  5. Run AMQP Consumer and observe messages in Eclipse IDE
  6. spring rabbitmq example consumer

    Here we can see that AMQP Consumer receives each message one by one from RabbitMQ queue.

  7. RabbitMQ console is showing 0 messages in the queue
  8. spring rabbitmq amqp receiver

    Here we can observe that RabbitMQ queue has 0 messages that means AMQP Consumer has received all messages successfully.

NOTE: With this knowledge of Spring AMQP RabbitMQ Messaging, you can read more about Spring AMQP API and learn new things. And also go through RabbitMQ Server documentation to get more details about Exchanges, Queues etc.

NOTE: As I told you in my previous post, both Spring AMQP API and RabbitMQ Server are from The Pivotal Team.

That’s it all about developing Spring AMQP RabbitMQ Messaging Example. We will discuss and develop Spring AMQP ActiveMQ Messaging Example in my coming posts.

Further Reading: Apache ActiveMQ.

Comments

  1. Savani says:

    Could you please create Spring Boot Rabbit MQ example ?

    Regards,
    Prateek

  2. uttam says:

    Thanks RAMBABU for a great example for creating RabbitMQ example… Below are few points where i need your help.

    a) I am having a requirement to send a complete user defined object in queue and consuming at listener side..
    b) Need to have load balancing configuration on queue.

    Thanks in advance.
    Uttam

  3. Mehmet Tayyar Kuyucu says:

    Hey Rambabu,
    Thank you for this great tutorial . I need to also implemet when error occure in message listener. How can i put task to queue again. And also want to count how many error has been occured for each task.

    Thanks your help

  4. Ivan says:

    what are the dependencies? bro ?

    1. Rambabu says:

      Oh thanks for catching that one. Added misisng pom.xml. Please Check it now.

      Ram

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages