RabbitMQ2

Tutorial: RabbitMQ with Spring Framework

by on April 1, 2013 8:41 am

In this quick tutorial, we will create a RabbitMQ Template to send messages to an exchange.

The exchange we are working to send a message to is named “TUTORIAL-EXCHANGE” with a routing key of “my.routingkey.1″. We will then create an AMQP listener in order to listen for messages in the same exchange using the pattern of the sender’s routing key.

We can easily hook up the listener to a Spring Batch Admin project to process asynchronous jobs. This is similar to using JMS message-driven beans without a J2EE container, and saves a lot of cost.

The Steps

1. Install RabbitMQ server

You may follow the instructions on the following page to install the RabbitMQ server on your windows computer. It will ask you to download erlan software – go ahead and install that first.

2. Create a Spring MVC project using Spring Tool Suite
3. Add the two following dependencies to your POM.xml’s dependencies section:
<dependency>
	<groupId>org.springframework.amqp</groupId>
	<artifactId>spring-amqp</artifactId>
	<version>1.1.4.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.amqp</groupId>
	<artifactId>spring-rabbit</artifactId>
	<version>1.1.1.RELEASE</version>
</dependency>
4. In your resources folder, create the file rabbit-sender-context.xml
<?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">
	<!--  first following line creates a rabbit connection factory with specified parameters -->
	<rabbit:connection-factory id="connectionFactory" host="localhost" username="guest" password="guest" />
	<!-- obtain admin rights to create the an exchange -->
	<rabbit:admin connection-factory="connectionFactory" />

	<!-- create a bean which can send message to TUTORIAL_EXCHANGE for the Java program to call -->
	<rabbit:template id="tutorialTemplate" connection-factory="connectionFactory"  exchange="TUTORIAL-EXCHANGE"/>
</beans>
5. Create a listener class com.keyhole.amqp.TutorialListener
package com.keyhole.amqp;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
/**
 * This class implements org.springframework.amqp.core.MessageListener.
 *  It is tied to TUTORIAL_EXCHANGE and listing to an anonomous queue
 *  which picks up message in the  TUTORIAL_EXCHANGE with a routing pattern of
 *  my.routingkey.1  specified in rabbt-listener-contet.xml file.
 */
public class TutorialListener implements MessageListener {
	public void onMessage(Message message) {
	String messageBody= new String(message.getBody());
		System.out.println("Listener received message----->"+messageBody);
	}
}
6. In the resources directory, create the file rabbit-listener-context.xml:
<? 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="guest" password="guest" />
    <rabbit:admin connection-factory="connectionFactory" />
    <!-- Create myAnonymousQueue queue -->
    <rabbit:queue id="myAnonymousQueue" />
    <!-- create myExchange and bind myAnonymousQueue with my.routingkey.1 to the TUTORIAL-EXCHANGE-->
    <rabbit:topic-exchange id="myExchange" name="TUTORIAL-EXCHANGE">
        <rabbit:bindings>
            <rabbit:binding queue="myAnonymousQueue" pattern="my.#.*"></rabbit:binding>
        </rabbit:bindings>
    </rabbit:topic-exchange>
    <!-- instantiate TutorialListener -->
    <bean id="aListener" class="com.keyhole.amqp.TutorialListener" />
    <!-- glue the listener and myAnonymousQueue to the container-->
    <rabbit:listener-container id="myListenerContainer" connection-factory="connectionFactory">
        <rabbit:listener ref="aListener" queues="myAnonymousQueue" /></rabbit:listener-container>
</ beans>
7. Load the listener container
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TutorialListenerContainer {
	public static void main(String[] args) {
		ApplicationContext c1 = new ClassPathXmlApplicationContext("Rabbt-listener-contet.xml");

	}
}
8. Send Messages
/**
 * Create a template of the tutorial bean defined in the XML file and send 10 message
 * to the TUTORIAL-EXCHANGE configured in the rabbt-listener-contet.xml file with the routing key
 *"my.routingkey.1"
 *
 */
public class TutorialSender {
	public static void main(String[] args) throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext("rabbit-sender-context.xml");//loading beans
		AmqpTemplate aTemplate = (AmqpTemplate) context.getBean("tutorialTemplate");// getting a reference to the sender bean

		for (int i = 0; i < 10; i++)
			aTemplate.convertAndSend("my.routingkey.1", "Message # " +i +" on "+ new Date());// send
	}
}
//end of TutorialSender
9. Run TutorialListenerContainer as a Java application.
10. Run TutorialSender as a Java application.

You will then see the listener display the received messages.

11. Change patterns using wild cards.

Try to change the pattern=”my.routingkey.1″ to pattern=”my.#.*” in rabbit-listener-context.xml. Run the listener and sender again.

The wild card * represents any one character, while # represents any number of characters between the dots in the pattern but not in the routing keys.

Optional:

If you want to manage a RabbitMQ server, you can optionally enable the web interface. Follow these steps:

1. Click the Windows Start button on lower left corner of your computer and type: cmd and hit return.

2. Now you see a black DOS window. Type: cd C:\Program Files\RabbitMQ Server\rabbitmq_server-3.0.4\sbin into the sbin directory.

3. Type: rabbitmq-plugins enable rabbitmq_management.

I hope you find this quick tutorial useful. Here is a link to a zip file of the source code. Good luck!

– Zhihua Douglas Dong, asktheteam@keyholesoftware.com

  • Share:

9 Responses to “Tutorial: RabbitMQ with Spring Framework”

  1. Sumanth says:

    I am getting below error when I run TutorialSender as JavaApplication which is mentioned at step 10.

    Do we have to mention connection params ?

    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6e293a: defining beans [connectionFactory,org.springframework.amqp.rabbit.core.RabbitAdmin#0,tutorialTemplate]; root of factory hierarchy
    Exception in thread “main” org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
    at org.springframework.amqp.rabbit.connection.RabbitUtils.convertRabbitAccessException(RabbitUtils.java:106)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:163)
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:228)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils$1.createConnection(ConnectionFactoryUtils.java:77)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.doGetTransactionalResourceHolder(ConnectionFactoryUtils.java:121)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.getTransactionalResourceHolder(ConnectionFactoryUtils.java:67)
    at org.springframework.amqp.rabbit.connection.RabbitAccessor.getTransactionalResourceHolder(RabbitAccessor.java:100)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:591)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:329)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:358)
    at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:346)
    at rabbitmq.sender.TutorialSender.main(TutorialSender.java:21)
    Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.rabbitmq.client.ConnectionFactory.createFrameHandler(ConnectionFactory.java:445)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:504)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:545)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:160)
    … 10 more

    • Douglas says:

      The connection params are specified in the rabbit-sender-context.xml file:

      You may need to start the Rabbitmq server from your computer’s Windows menu. See the optional step in the blog to check if the server is running.

  2. Anonymous says:

    Seems like you have copied the sender configuration file contents for listener configuration as well.. by mistake??

  3. Douglas says:

    Yes, the mistake has been corrected. I also added a link to the source code.

  4. David says:

    Excellent tutorial, thanks a lot!

  5. Shrivats says:

    Thanks a lot. Your tutorial was awesome.

    Just a trivial suggestion : the rabbit-listener-context.xml has a couple of spacing issues.

  6. [...] previously published a brief tutorial showing how to set up a Spring RabbitMQ Template. Now, let’s take a step back for a broader view [...]

  7. akz says:

    Nice one.

  8. suyog says:

    excellent tutorial

Leave a Reply

Things Twitter is Talking About
  • Interested in #Backbone & #Marionette but not sure where to start? Check out the Marionette-Require-Boilerplate: http://t.co/XDj43BwSS3 #SPA
    April 22, 2014 at 4:50 PM
  • Responsive Design can help in giving your users a consistent app experience across devices. Quick tutorial - http://t.co/BDrT5LvgRo
    April 22, 2014 at 2:31 PM
  • Tips & tricks to save time in the #Eclipse IDE - http://t.co/uGgCkchwNk (keystroke combos, navigation, time tracking & more)
    April 22, 2014 at 8:40 AM
  • Join us! Looking to add to our team a developer w/ advanced #JavaScript & #NodeJS exp (& love of tech variety). Info: http://t.co/cC9CU1RCF9
    April 21, 2014 at 7:35 PM
  • Looking into #ExtJS but don't know where to start? Check out our video tutorial series to find your way around - http://t.co/XFYDT6YNWA
    April 21, 2014 at 4:35 PM
  • We've been tinkering with JS library Famo.us since its public release 4/10. What we've learned so far via a POC app - http://t.co/S77TSKHDKd
    April 21, 2014 at 2:03 PM
  • RT @CompSciFact: Rivest, Shamir, and Adleman published the RSA public key cryptography algorithm in 1978.
    April 21, 2014 at 11:13 AM
  • DYK? When we share/RT/blog/etc, it doesn't mean that Keyhole endorses it - we just like variety of opinions! Info: http://t.co/MXhB9lE9tV
    April 19, 2014 at 3:01 PM
  • A huge welcome to Justin Graber who joined the Keyhole team this week!
    April 18, 2014 at 3:25 PM
  • Pssst... @kc_dc early bird pricing ends on Sunday. Shoot us a note if you want to save 10% off of your ticket with our sponsor promo code!
    April 18, 2014 at 2:49 PM
  • Join our team! Looking for a developer w/ advanced #JavaScript & #NodeJS experience (& love of tech variety). Info: http://t.co/cC9CU1RCF9
    April 18, 2014 at 11:21 AM
  • .@befamous has huge potential to make HTML5/JS/CSS web pages feel as native apps. Here's our inital tech takeaways - http://t.co/S77TSKHDKd
    April 18, 2014 at 9:50 AM
  • Why to use AngularUI Router instead of ngRoute - http://t.co/tBnj5ZCkOw
    April 17, 2014 at 7:55 PM
  • RT @joemccann: Total Number of GitHub Repositories by Programming Language http://t.co/30cekDsE4s
    April 17, 2014 at 4:25 PM
  • JSF + AngularJS = AngularFaces? http://t.co/mXvOTwVbb6 // Interesting insight. Thoughts?
    April 17, 2014 at 3:45 PM
  • RT @MikeGelphman: Great news, guys: @TobiasRush founder of @eyeverify is our latest @MobileMidwest speaker addition http://t.co/8fE8oNfPnX
    April 17, 2014 at 1:35 PM
  • .@befamous was released publicly 4/10 & we've been tinkering with it since. What we've learned so far via a POC app - http://t.co/S77TSKHDKd
    April 17, 2014 at 8:33 AM
  • Famo.us' main idea is for HTML5/JS/CSS web pages to feel like native mobile apps. So, @zachagardner tried it out - http://t.co/S77TSKHDKd
    April 15, 2014 at 6:40 PM
  • @JKFeldkamp Thanks for your RT! Such a neat technology. We're so excited @zachagardner is getting involved. Have a great day!
    April 15, 2014 at 4:00 PM
  • .@zachagardner has been tinkering with Famo.us (@befamous) released 4/10. What he's learned so far with a POC app - http://t.co/1jMqBfZURn
    April 15, 2014 at 2:29 PM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2013 Keyhole Software, LLC. All rights reserved.