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
  • Check out our newest blog: #JAXB – A Newcomer’s Perspective, Part 1 http://t.co/Ki9G04HV5e
    July 22, 2014 at 1:22 PM
  • New post on the Keyhole blog by Mark Adelsberger: #JAXB – A Newcomer’s Perspective, Part 1 http://t.co/Ki9G04HV5e
    July 21, 2014 at 2:27 PM
  • If you're a Java dev, you're likely familiar with Annotations. But have you created your own #Java Annotations? Ex - http://t.co/BgCsYjxZKF
    July 18, 2014 at 12:10 PM
  • RT @gamasutra: Don't Miss: Unconventional Tips for Improving your Programming Skills http://t.co/6TFox7CKHU
    July 16, 2014 at 3:20 PM
  • We're about to send out our free monthly tech newsletter. Dev tips/articles via email. Not on the list yet? Sign up - http://t.co/F8h0NSiicZ
    July 15, 2014 at 11:57 AM
  • Have you ever tried creating your own #Java annotations? See a situation where it was beneficial - http://t.co/BgCsYjxZKF
    July 15, 2014 at 8:36 AM
  • There's a new post on the Keyhole blog by @jhackett01: Creating Your Own #Java Annotations - http://t.co/BgCsYjxZKF
    July 14, 2014 at 1:43 PM
  • We love development! Have you seen our weekly team blog? We show how to be successful with the tech we use. See it - http://t.co/nlRtb1XNQH
    July 12, 2014 at 2:35 PM
  • Rapid appdev has a bad rep, but there are ways to bring development time down the right way. Don't Fear the Rapid - http://t.co/aTPcAKOj0r
    July 11, 2014 at 3:10 PM
  • Automated Testing is great for dev, but does bring a set of challenges (especially for #agile teams). Success tips: http://t.co/1acl1ngO7i
    July 11, 2014 at 12:16 PM
  • This is fantastic - One small step for Google, one giant leap for empowering girls to code: http://t.co/R90V5DBkv1
    July 10, 2014 at 2:52 PM
  • #RabbitMQ: messaging software built on AMQP protocol. Learn relevant concepts & how to avoid common "gotchas" here: http://t.co/ZwMXlhKyX8
    July 10, 2014 at 9:31 AM
  • A huge welcome to Brian Wetzel who joins the Keyhole team today!
    July 10, 2014 at 8:50 AM
  • Seen our newest blog? @joshuarob01 talks the challenges #Agile teams face in automated testing & how to solve them: http://t.co/1acl1ngO7i
    July 9, 2014 at 3:51 PM
  • How can we ensure that we write unit tests with sufficient coverage? Here are some tips for success in #unittesting - http://t.co/GGTEGEQFtk
    July 9, 2014 at 3:05 PM
  • Are you a .NET dev who likes working with #JavaScript, #Angular & a solid team? Join Keyhole: http://t.co/kWgVdxgvpG http://t.co/VLoeULthOE
    July 9, 2014 at 8:48 AM
  • Counting down until the Keyhole Team Happy Hour this evening @ the District. Pour House + Kitchen... one more hour!
    July 8, 2014 at 4:15 PM
  • Code For Maintainability So The Next Developer Doesn't Hate You - http://t.co/FWTMF7Pixd 8 helpful tips to do so.
    July 8, 2014 at 2:05 PM
  • So glad you enjoyed it! @AssertAgile: "Nice article, sounds familiar to me: Lessons Learned in Automated Testing - http://t.co/1acl1ngO7i"
    July 8, 2014 at 1:54 PM
  • Good tutorial: creating a TV show tracker with #AngularJS, Bootstrap, Node, MongoDB, Passport & gulp.js - http://t.co/meXZDazxFr
    July 8, 2014 at 12:07 PM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.