Spring ActiveMQ Example (Part 2)

Filed Under: JMS

This is the second part in the Spring ActiveMQ example tutorial. Please head over to the first part at Spring AMQP ActiveMQ Tutorial.

Spring ActiveMQ Example

We will have following sections in this Spring ActiveMQ Example post.

  • Introduction
  • Develop Spring AMQP Messaging Application With ActiveMQ
  • Develop Test client for Spring AMQP ActiveMQ Messaging Application
  • Test Spring AMQP Messaging Application With ActiveMQ

Introduction

We have already discussed some “Spring AMQP Basics” Theoretically and “How to install and setup ActiveMQ Server” in my previous posts. Please refer them in the following:

In this post, we are going to develop a Spring AMQP ActiveMQ Messaging application. Let us start it now.

Develop Spring AMQP Messaging Application With ActiveMQ

Let us start developing a Spring AMQP ActiveMQ Messaging application using Maven, Eclipse IDE and ActiveMQ Server. It is same for all other Java IDEs.

Please do the following the steps one by one:

  • Develop Spring ActiveMQ AMQP Publisher program
  • 
    package com.tp.jms.activemq;
    
    import javax.annotation.PostConstruct;
    import javax.jms.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jms.core.JmsTemplate;
    import org.springframework.jms.core.MessageCreator;
    import org.springframework.stereotype.Component;
    @Component
    public class ActiveMQMessageProducer {
        protected static final String MSG_COUNT = "messageCount";
        @Autowired
        private JmsTemplate jmsTemplate = null;
    
        @PostConstruct
        public void generateMessages() throws JMSException 
        {
            for (int messageCount = 0; messageCount < 10; messageCount++) 
            {
                final String text = "TP Message " + messageCount;
                jmsTemplate.send(new MessageCreator() 
                {
                    public Message createMessage(Session session) throws JMSException
                    {
                        TextMessage textMessage = session.createTextMessage(text);
                        textMessage.setIntProperty(MSG_COUNT, messageCount);              
                        return textMessage;
                    }
                });
            }
        }
    }
    
  • Develop JMS Asynchronous JMS Consumer by using Spring JMS APIs MDPs.
  • 
    package com.tp.jms.activemq;
    
    import java.util.concurrent.atomic.AtomicInteger;
    import javax.jms.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ActiveMQMessageListener implements MessageListener 
    { 
        @Autowired
        private AtomicInteger count = null;
        public void onMessage(Message message)
        {
            try 
            {   
                if (message instanceof TextMessage) 
                {
                    TextMessage txtMsg = (TextMessage)message;
                    System.out.println("Received message from Destination : " +
                                                          txtMsg.getText());				
                    count.incrementAndGet();
                }
            } 
            catch (JMSException e) { }
        }
    
    }
    
  • Final pom.xml file
  • 
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.tp</groupId>
        <artifactId>simple-jms</artifactId>
        <version>1.0.2</version>
    	<properties>
    	<java-version>1.6</java-version>
    	<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
    	<org.aspectj-version>1.6.10</org.aspectj-version>
    	<org.slf4j-version>1.6.6</org.slf4j-version>
    	<activemq.version>5.2.0</activemq.version>
    	</properties>
    	<dependencies>
    	<!-- Spring -->
    	  <dependency>
    	    <groupId>org.springframework</groupId>
    		<artifactId>spring-context</artifactId>
    		<version>${org.springframework-version}</version>
    		<exclusions>
    		  <!-- Exclude Commons Logging in favor of SLF4j -->
    			<exclusion>
    		 	  <groupId>commons-logging</groupId>
    			  <artifactId>commons-logging</artifactId>
    			 </exclusion>
    		  </exclusions>
    		</dependency>
    		<dependency>
    		  <groupId>org.springframework</groupId>
    		  <artifactId>spring-webmvc</artifactId>
    		  <version>${org.springframework-version}</version>
    		</dependency>
    		 <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jms</artifactId>
                <version>${org.springframework-version}</version>
            </dependency>
         		
            <!-- AspectJ -->
    	<dependency>
    	  <groupId>org.aspectj</groupId>
    	  <artifactId>aspectjrt</artifactId>
    	  <version>${org.aspectj-version}</version>
    	</dependency>	
    		
    	<!-- Logging -->
    	<dependency>
    	  <groupId>org.slf4j</groupId>
    	  <artifactId>slf4j-api</artifactId>
    	  <version>${org.slf4j-version}</version>
    	</dependency>
    	<dependency>
    	  <groupId>org.slf4j</groupId>
    	  <artifactId>jcl-over-slf4j</artifactId>
    	  <version>${org.slf4j-version}</version>
    	  <scope>runtime</scope>
    	</dependency>
    	<dependency>
    	  <groupId>org.slf4j</groupId>
    	  <artifactId>slf4j-log4j12</artifactId>
    	  <version>${org.slf4j-version}</version>
    	  <scope>runtime</scope>
    	</dependency>
    	<dependency>
    		<groupId>log4j</groupId>
    		<artifactId>log4j</artifactId>
    		<version>1.2.15</version>
    		<exclusions>
    			<exclusion>
    				<groupId>javax.mail</groupId>
    				<artifactId>mail</artifactId>
    			</exclusion>
    			<exclusion>
    				<groupId>javax.jms</groupId>
    			<artifactId>jms</artifactId>
    			</exclusion>
    			<exclusion>
    				<groupId>com.sun.jdmk</groupId>
    				<artifactId>jmxtools</artifactId>
    			</exclusion>
    			<exclusion>
    			<groupId>com.sun.jmx</groupId>
    				<artifactId>jmxri</artifactId>
    			</exclusion>
    		</exclusions>
    		<scope>runtime</scope>
    	</dependency>
    		<!-- @Inject -->
    	<dependency>
    		<groupId>javax.inject</groupId>
    		<artifactId>javax.inject</artifactId>
    			<version>1</version>
    	</dependency>
    			
    	<!-- Servlet -->
    	<dependency>
    		<groupId>javax.servlet</groupId>
    		<artifactId>servlet-api</artifactId>
    		<version>2.5</version>
    		<scope>provided</scope>
    	</dependency>
    	<dependency>
    		<groupId>javax.servlet.jsp</groupId>
    		<artifactId>jsp-api</artifactId>
    		<version>2.1</version>
    		<scope>provided</scope>
    	</dependency>
    	<dependency>
    		<groupId>javax.servlet</groupId>
    		<artifactId>jstl</artifactId>
    		<version>1.2</version>
    	</dependency>
    	<!-- Test -->
    	<dependency>
    		<groupId>junit</groupId>
    		<artifactId>junit</artifactId>
    		<version>4.7</version>
    		<scope>test</scope>
    	</dependency> 
    	
    	<!-- ActiveMQ -->
    	<dependency>
               <groupId>org.apache.activemq</groupId>
               <artifactId>activemq-core</artifactId>
               <version>${activemq.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-optional</artifactId>
                <version>${activemq.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.xbean</groupId>
                <artifactId>xbean-spring</artifactId>
                <version>3.7</version>
            </dependency>
            
           <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${org.springframework-version}</version>
            </dependency> 
                   
    	</dependencies>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <version>2.9</version>
                    <configuration>
                        <additionalProjectnatures>
                            <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                        </additionalProjectnatures>
                        <additionalBuildcommands>
                            <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                        </additionalBuildcommands>
                        <downloadSources>true</downloadSources>
                        <downloadJavadocs>true</downloadJavadocs>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.5.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <compilerArgument>-Xlint:all</compilerArgument>
                        <showWarnings>true</showWarnings>
                        <showDeprecation>true</showDeprecation>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.2.1</version>
                    <configuration>
                        <mainClass>org.test.int1.Main</mainClass>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    

Develop Test client for Spring AMQP ActiveMQ Messaging Application

  • Develop a Test application
  • 
    package com.tp.jms.activemq;
    import static org.junit.Assert.*;
    import java.util.concurrent.atomic.AtomicInteger;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class ActiveMQJmsMessageListenerTest {
        @Autowired
        private AtomicInteger count = null;    
        @Test
        public void testMessage() throws Exception {
            assertEquals(10, count.get());
        }    
    }
    

    NOTE:- As this Unit test name is ActiveMQJmsMessageListenerTest, then @ContextConfiguration annotation searches for ActiveMQJmsMessageListenerTest-context.xml file in same package structure.

  • Final Project Structure
  • Here we can see our Spring AMQP ActiveMQ Messaging application’s final Eclipse project structure.

    spring activemq example

Test Spring AMQP Messaging Application With ActiveMQ

In this section, we will test our Spring AMQP ActiveMQ Messaging application using our Test client developed in the previous section.

  • Observe above Test program. We are using asserting concept to test the message count
  • 
    assertEquals(10, count.get());
    

    If both published and consumed messages are NOT equal then the below does not throw AssertError.

  • Run the Unit and see the successful message.
  • Right click on the Test program and run it as Junit test.

  • To see message in ActiveMQ Admin console, please comment listener configuration in XML file
  • 
    <jms:listener-container container-type="default" 
           connection-factory="consumerJmsConnectionFactory" acknowledge="auto">
    	 <jms:listener destination="jms/TPActiveMQQueue" 
    	               ref="activeMQMessageListener" />
    </jms:listener-container>
    

    And run test class again and observe ActiveMQ Admin console for 10 messages:

    spring activemq queue msgs

  • And run test class again and observe ActiveMQ Admin console for 10 messages:
  • Unit test will fail as we don’t consume any messages. But that is fine as we need see messages in ActiveMQ Queue.

That’s it all about developing Spring AMQP ActiveMQ Messaging Example.

Comments

  1. Adam says:

    Thank you for these great explanations, but does this example actually use Spring AMQP?

    It seems purely Spring JMS that does not use AMQP protocol, am I missing anything?

  2. kavita says:

    Can i get the ActiveMQJmsMessageListenerTest-context.xml file, i am facing some issues.

  3. Manish Arora says:

    Hi,

    In the below line i am getting compile time error “Cannot refer to the non-final local variable messageCount defined in an enclosing scope”

    textMessage.setIntProperty(MSG_COUNT, messageCount);

    Can you please explain why i am getting this error and how your code is working fine ?

    1. Apurva says:

      Modify your code like this:

      final int count = messageCount;
      jmsTemplate.send(new MessageCreator()
      {
      public Message createMessage(Session session) throws JMSException
      {
      TextMessage textMessage = session.createTextMessage(text);
      textMessage.setIntProperty(MSG_COUNT, count);
      return textMessage;
      }
      });

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages