JMS study notes (4) Spring combined with ActiveMQ

1. Experimental environment

 1.jdk1.6

  2.spring 2.5

  3.apache-activemq-5.10.0


Two point-to-point message model Send and receive messages example


ProductService responsible for sending messages


package com.testactivemq;
import javax.jms.JMSException;
import javax.jms.Message;

import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class ProductService {
  private  JmsTemplate jmsTemplate;
  
  
  /****
   * Send information to the default queue, which is the message queue injected into jmsTemplate
   * @param msg
   * @return
   */
    public void sendMessage(final String msg) {
      String destination =  jmsTemplate.getDefaultDestination().toString();
      System.out.println("Sent message to queue " +destination+ ": " + msg);
     
      jmsTemplate.send(new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
        	 TextMessage tx=session.createTextMessage();
        	 tx.setText(msg);
         return tx;
        }
      });
   
    }
    /***
     * Send a message to the specified queue
     * @param destination
     * @param msg
     */
    public void sendMessage(String destination,final String msg)
    {
    	
    	 System.out.println("Message sent to queue " +destination+ ": " + msg);
    	jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
            	 TextMessage tx=session.createTextMessage();
            	 tx.setText(msg);
            	 return tx;
               }
             });
    	
    }

public JmsTemplate getJmsTemplate() {
	return jmsTemplate;
}

public void setJmsTemplate(JmsTemplate jmsTemplate) {
	this.jmsTemplate = jmsTemplate;
}
  
}




The specific code of ConsumerService responsible for receiving messages
package com.testactivemq;
import javax.jms.JMSException;
import javax.jms.TextMessage;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
public class ConsumerService {

	private JmsTemplate jmsTemplate;
	 
	 /****
	  * Receive default messages
	  */
	 public void receive()
	 {
		
		 
		 TextMessage tm = (TextMessage)jmsTemplate.receive();
		 String destinationName=jmsTemplate.getDefaultDestination().toString();
		 try {
			System.out.println("Received message from queue " + destinationName + ": "+tm.getText());
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
	 }
	 
	 /***
	  * Receive the specified message queue
	  * @param destination
	  */
	 public void receive(String destination)
	 {
		 
		 TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
		 try {
				System.out.println("Received message from queue" + destination + ":"+tm.getText());
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
	 }
	 
	 public static void main(String[] args)
	 {
                  //Read the path of the spring configuration file
		 ApplicationContext ac = new FileSystemXmlApplicationContext("F:\\workerspace\\MyTest\\WEB-INF\\classes\\applicationContext.xml");
		 ProductService ps= (ProductService) ac.getBean("productService");
		 ConsumerService cs1=(ConsumerService) ac.getBean("consumerService");
		ps.sendMessage("Haha");
		 cs1.receive();
		 
		//The following is to send and read messages from the queue2 queue
		 ps.sendMessage("queue2", "萌萌达");
		 cs1.receive("queue2");
	 }
	 
	 public JmsTemplate getJmsTemplate() {
			return jmsTemplate;
		}

		public void setJmsTemplate(JmsTemplate jmsTemplate) {
			this.jmsTemplate = jmsTemplate;
		}
}




Add the following configuration information to the spring configuration file

<!-- Configure the JMS connection factory -->
    <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="failover:(tcp://localhost:61616)" />
    </bean>
     
    <!-- Define the message queue (Queue) -->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <!-- Set the name of the message queue-->
        <constructor-arg>
            <value>queue1</value>
        </constructor-arg>
    </bean>
     
     
    <!-- Configure the JMS template (Queue), the JMS tool class provided by Spring, which sends and receives messages. -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="queueDestination" />
        <property name="receiveTimeout" value="10000" />
    </bean>
	
	 <!-- Define the message queue (Queue) -->
    <bean id="queueDestination2" class="org.apache.activemq.command.ActiveMQQueue">
        <!-- Set the name of the message queue-->
        <constructor-arg>
            <value>queue2</value>
        </constructor-arg>
    </bean>
	
	 <!--queue message producer -->
    <bean id="productService" class="com.testactivemq.ProductService">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
    </bean>
 
    <!--queue message consumer -->
    <bean id="consumerService" class="com.testactivemq.ConsumerService">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
    </bean>



The effect of running the main method in ConsumerService is as follows.






The point-to-point message model is as follows. In addition to the above receiving message method, Spring JMS provides the mode code and configuration of message monitoring as follows

package com.testactivemq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
 
public class QueueMessageListener implements MessageListener {
        //When a message is received, this method is automatically called, and it will stay in the process after running.
    public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
        	 String destination=tm.getJMSDestination().toString();
            System.out.println("Received ["+destination+"] text message: " + tm.getText());
        } catch (JMSException e) {
            e.printStackTrace ();
        }
    }
 
}



Configure the listener container and listener in the spring configuration file
<!-- Configure message queue listener (Queue) -->
    <bean id="queueMessageListener" class="com.testactivemq.QueueMessageListener" />
    
     <!-- Message listening container (Queue), configure the connection factory, the listening queue is queue2, and the listener is the listener defined earlier -->
    <bean id="jmsContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="queueDestination2" />
        <property name="messageListener" ref="queueMessageListener" />
    </bean>


public static void main(String[] args)
	 {
		 ApplicationContext ac = new FileSystemXmlApplicationContext("F:\\workerspace\\MyTest\\WEB-INF\\classes\\applicationContext.xml");
		 ProductService ps= (ProductService) ac.getBean("productService");
		 ConsumerService cs1=(ConsumerService) ac.getBean("consumerService");
				 
		//The following is to send a message from the queue2 queue, and the onMessage method of reading the message is automatically executed in the QueueMessageListener
		 ps.sendMessage("queue2", "萌萌达");
			 }


The effect after running is as follows



The example of sending and receiving messages of the two topic message model is

responsible for publishing the topic (message publisher) TopicProvider code is as follows

package com.testactivemq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
 
public class TopicProvider {
 
    private JmsTemplate topicJmsTemplate;
 
    /**
     * Publish a message to the specified topic
     *
     * @param topic
     * @param msg
     */
    public void publish(final String topic, final String msg) {
 
    	
        topicJmsTemplate.send(topic, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                System.out.println("The topic is [" + topic + "], the message content is: " + msg);
                return session.createTextMessage(msg);
            }
        });
    }
    
    public static void main(String[] args)
	 {
		 ApplicationContext ac = new FileSystemXmlApplicationContext("F:\\workerspace\\MyTest\\WEB-INF\\classes\\applicationContext.xml");
		 TopicProvider tp= (TopicProvider) ac.getBean("topicProvider");
           //The name of the test_topic topic is the identification mark of the topic
		 tp.publish("test_topic", "Momada");
		
	 }
 
    public void setTopicJmsTemplate(JmsTemplate topicJmsTemplate) {
        this.topicJmsTemplate = topicJmsTemplate;
    }
 
}



Responsible for receiving subscribed messages (message listener)

package com.testactivemq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
 * The same code as the queue listener.
 */
public class TopicMessageListener implements MessageListener {
 
	public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
        	 String destination=tm.getJMSDestination().toString();
            System.out.println("Received ["+destination+"], text message: " + tm.getText());
        } catch (JMSException e) {
            e.printStackTrace ();
        }
    }
 
}



Add the following code to the spring configuration

<!-- Define the message topic (Topic) -->
    <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg>
            <value>test_topic</value>
        </constructor-arg>
    </bean>
    <!-- Configure JMS template (Topic), pubSubDomain="true"-->
    <bean id="topicJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="topicDestination" />
        <property name="pubSubDomain" value="true" />
        <property name="receiveTimeout" value="10000" />
    </bean>
    <!--topic message publisher -->
    <bean id="topicProvider" class="com.testactivemq.TopicProvider">
        <property name="topicJmsTemplate" ref="topicJmsTemplate"></property>
    </bean>
    
    <!-- Message topic listener and topic listener container, multiple topic listener containers can be configured, that is, multiple subscribers -->
    <!-- Message topic listener (Topic) -->
    <bean id="topicMessageListener" class="com.testactivemq.TopicMessageListener" />
    <!-- Topic listener container (Topic), subscriber 1 -->
    <bean id="topicJmsContainer1"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="topicDestination" />
        <property name="messageListener" ref="topicMessageListener" />
    </bean>
    
   <!-- Topic listener container (Topic), subscriber 2 -->	
    <bean id="topicJmsContainer2"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="topicDestination" />
        <property name="messageListener" ref="topicMessageListener" />
    </bean>



Run the main method in TopicProvider, the effect is as follows



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326621905&siteId=291194637