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:

10 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

  9. Jared says:

    Excellent tutorial. straight to the point no fluff.
    Thanks for the help.

Leave a Reply

Things Twitter is Talking About
  • We send out our free monthly tech newsletter tomorrow - dev tips/articles via email. Not on the list? Sign up: http://t.co/h8kpjn419s
    September 16, 2014 at 2:58 PM
  • Want to chuckle? If programming languages were vehicles -http://t.co/quqHsUFCtR #funny
    September 16, 2014 at 11:41 AM
  • In Part 2 of our series on creating your own annotations, learn about processing #Java annotations using Reflection: http://t.co/DJZvQuarkc
    September 16, 2014 at 9:06 AM
  • Don't miss @jhackett01's newest post on the Keyhole blog - Processing #Java Annotations Using Reflection: http://t.co/E1lr3RmjI7
    September 15, 2014 at 12:02 PM
  • We're pretty excited - Keyhole's #BikeMS team raised 158% of their fundraising goal to benefit @MidAmericaMS. Plus, they had a great ride!
    September 15, 2014 at 10:38 AM
  • A huge welcome to David Kelly (@rheomatic) who officially joins the Keyhole team today! :-)
    September 15, 2014 at 10:00 AM
  • Sending warm thoughts to @eastlack, @cdesalvo, @wdpitt & all participating in #BikeMS this AM. Thanks for helping in the fight against MS!
    September 13, 2014 at 8:10 AM
  • .@rheomatic We are so excited to have you joining the team! Welcome :-)
    September 12, 2014 at 4:11 PM
  • As the official holiday is a Saturday, we're celebrating today! Happy (early) #ProgrammersDay to you! http://t.co/1CvUfrzytE
    September 12, 2014 at 1:55 PM
  • Tomorrow @cdesalvo, @eastlack, & @wdpitt are riding #BikeMS to benefit @MidAmericaMS. You can get involved, too - http://t.co/9boQwEUxth
    September 12, 2014 at 11:00 AM
  • RT @AgileDevs: 5 tips for great code reviews http://t.co/9PdbtEv0z8
    September 11, 2014 at 2:53 PM
  • The BEMs of Structuring #CSS - http://t.co/159suYtfx6 A quick introduction to the Block Element Modifier methodology.
    September 10, 2014 at 2:49 PM
  • A huge welcome to Joseph Post (@jsphpst) who has joined the Keyhole team this week!
    September 10, 2014 at 9:52 AM
  • @TheGrisExplores Absolutely, and thanks for the compliment! Here's an article that you might find helpful, too - http://t.co/7oxpaohCS1
    September 9, 2014 at 2:22 PM
  • Express.js seems to be the top pick! MT @TheGrisExplores: "what's your fave server-side MVC framework for NodeJS when SPA is not an option?"
    September 9, 2014 at 1:56 PM
  • RT @TheGrisExplores: Yo @KeyholeSoftware dudes and dudettes: what is your favorite server-side MVC framework for NodeJS when SPA is not an …
    September 9, 2014 at 1:15 PM
  • There is a new post on the Keyhole blog by @brianletteri - The BEMs of Structuring CSS: http://t.co/159suYtfx6
    September 9, 2014 at 12:12 PM
  • Know a bright grad? We're looking for a business support / recruiting representative to join our team in Kansas City: http://t.co/GDvFVmoMF9
    September 8, 2014 at 11:31 AM
  • A huge welcome to @jeremygard who joins the Keyhole team today!
    September 8, 2014 at 8:40 AM
  • 8 tips to help you code for maintainability so the next developer doesn't hate you (which we think is important) - http://t.co/Aoe931WLzb
    September 5, 2014 at 2:40 PM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.