Tutorial: RabbitMQ with Spring Framework

Zhihua Douglas Dong Java, Spring, Tutorial 13 Comments

Attention: The following article was published over 11 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

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, [email protected]

0 0 votes
Article Rating
Subscribe
Notify of
guest

13 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments