Tutorial: RabbitMQ with Spring Framework

Zhihua Douglas Dong Java, Spring, Tutorial 13 Comments

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:
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"/>
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:binding queue="myAnonymousQueue" pattern="my.#.*"></rabbit:binding>
    <!-- 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
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.


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

About the Author

Zhihua Douglas Dong

Share this Post

Comments 13

  1. Sumanth

    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

    1. Douglas

      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

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

  3. Shrivats

    Thanks a lot. Your tutorial was awesome.

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

  4. Pingback: Messaging with RabbitMQ | Keyhole Software

  5. Rajaneesh

    Can I have Java as Sender of message and Java Script as Receiver?

    Is Peer to Peer is possible with two java script or java clients ?

    See my requirement ,

    I have a online two player game , when game starts or ends or paused only I need message to my server .

    in remaining steps clients needs to exchange message directly without server call .

    is that possible?

  6. Deepak Aggarwal

    Excellent tutorial to start with. Every thing is crisp and clear.
    Appreciate if you throw more light on binding the messages.

Leave a Reply