ACTIVEMQ Study Notes (v)--send and receive messages using spring JMS

Source: Internet
Author: User
Tags gettext

ACTIVEMQ Study notes (iv)http://my.oschina.net/xiaoxishan/blog/380446 the use of native methods to send and receive messages from ACTIVEMQ. As you can see, every time you send and receive messages, you write a lot of repetitive code, and spring provides a much more convenient way for us, which is spring JMS. Let's start with an example. Includes the queue, the send and receive related spring configuration of the subject message, the code, the test.

In this case, the messages are sent and received in a project.

1. Using MAVEN to manage dependent packages
<dependencies><dependency><groupid>junit</groupid><artifactid>junit</ artifactid><version>4.12</version><scope>test</scope></dependency>< Dependency><groupid>org.apache.activemq</groupid><artifactid>activemq-all</artifactid ><version>5.11.0</version></dependency><dependency><groupId> Org.springframework</groupid><artifactid>spring-jms</artifactid><version>4.1.4.release          </version></dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.4.RELEASE</version> </dependen Cy> </dependencies>


2. Sending and Receiving queue messages2.1Spring configuration file
<?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="/HTTP/ www.springframework.org/schema/beans        http:// Www.springframework.org/schema/beans/spring-beans.xsd "><!--  Configure JMS connection Factory  --><bean id=" ConnectionFactory " class=" Org.apache.activemq.ActiveMQConnectionFactory "><property name=" Brokerurl " value=" Failover: (tcp://localhost:61616)  /></bean><!--  Define Message Queuing (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 a JMS template (Queue), a spring-provided JMS tool class that sends and receives messages.  --><bean id= "Jmstemplate"  class= "Org.springframework.jms.core.JmsTemplate" &GT;&LT;property name= "ConnectionFactory"  ref= "ConnectionFactory"  /><property name= " Defaultdestination " ref=" queuedestination " /><property name=" ReceiveTimeout " value=" 10000 " /></bean><!--queue message producer  --><bean id=" Producerservice " class=" Guo.examples.mq02.queue.ProducerServiceImpl "><property name=" Jmstemplate " ref=" Jmstemplate " ></property></bean><!--Queue message Consumer  --><bean id= "Consumerservice"  class= " Guo.examples.mq02.queue.ConsumerServiceImpl "><property name=" Jmstemplate " ref=" Jmstemplate " ></property></bean>


2.2 Message Producer Code

From the code below, using spring JMS, you can reduce duplicate code (interface class Producerservice code omitted).

package guo.examples.mq02.queue;import javax.jms.destination;import javax.jms.jmsexception; import javax.jms.message;import javax.jms.session;import  org.springframework.jms.core.jmstemplate;import org.springframework.jms.core.messagecreator;public  Class producerserviceimpl implements producerservice {  private jmstemplate  jmsTemplate;    /**   *  send messages to the specified queue    */   public void sendmessage (destination destination, final string msg)  {     system.out.println ("To queue"  + destination.tostring ()  +  " Sent a message------------" + msg);     jmstemplate.send (destination, new  Messagecreator ()  {      public message createmessage (Session  session) &NBSP;THROWS&NBSP;JMSEXCEPTION&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;  return session.createtextmessage (msg);      }     });  }/** *  sends a message to the default queue  */  public void sendmessage ( FINAL&NBSP;STRING&NBSP;MSG)  {string destination =  jmstemplate.getdefaultdestination ( ). toString ();     system.out.println ("Send Message------------to queue"  +destination+  " &NBSP;+&NBSP;MSG);     jmstemplate.send (New messagecreator ()  {       public message createmessage (session session)  throws JMSException  {        return session.createtextmessage (msg);       }    });  }  public void  Setjmstemplate (jmstemplate jmstemplate)  {    this.jmsTemplate =  jmstemplate;  }}

2.3 Message Consumer Code
Package Guo.examples.mq02.queue;import Javax.jms.destination;import Javax.jms.jmsexception;import Javax.jms.textmessage;import Org.springframework.jms.core.jmstemplate;public class ConsumerServiceImpl implements Consumerservice {Private Jmstemplate jmstemplate;/** * Accept message */public void receive (Destination Destination) {TextMessage T m = (textmessage) jmstemplate.receive (destination); try {System.out.println ("from queue" + destination.tostring () + "message received: \ t" + Tm.gettext ());} catch (JMSException e) {e.printstacktrace ();}} public void Setjmstemplate (Jmstemplate jmstemplate) {this.jmstemplate = Jmstemplate;}}


2.4 Queue message Snooping

When receiving a message, the Spring JMS also provides a pattern for message listening, in the same way as in section 2.3, and the corresponding configuration and code are given below.

Spring Configuration

<!--define Message Queuing (queue), we listen for a new queuing, queue2--><bean id= "QueueDestination2" class= " Org.apache.activemq.command.ActiveMQQueue "><!--Set the name of the message queue--><constructor-arg><value>queue2 </value></constructor-arg></bean><!--Configure the Message Queue Listener (queue), given below the code, there is only one OnMessage method-->< Bean id= "Queuemessagelistener" class= "Guo.examples.mq02.queue.QueueMessageListener"/><!--message listening container (queue), Configure the connection factory, listen for the queue is queue2, listener is the listener defined above--><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>

Listening Class Code

Package Guo.examples.mq02.queue;import Javax.jms.jmsexception;import Javax.jms.message;import Javax.jms.messagelistener;import Javax.jms.textmessage;public class Queuemessagelistener implements MessageListener {//When the message is received, the method is called automatically. public void OnMessage (Message message) {TextMessage TM = (textmessage) message;try {System.out.println (" Consumermessagelistener received a text message: \ t "+ tm.gettext ());} catch (JMSException e) {e.printstacktrace ();}}}



3. Subject message sending and receiving

The main difference between the topic (TOPIC) and the queue message when using spring JMS is that the "Pubsubdomain" is set to true in Jmstemplate. If true, it is topic, or the queue if it is false or default.

<property name= "Pubsubdomain" value= "true"/>


3.1Spring Configuration
<!--  Define message subject (TOPIC)  --><bean id= "Topicdestination"  class= " Org.apache.activemq.command.ActiveMQTopic "><constructor-arg><value>guo_topic</value></ constructor-arg></bean><!--  Configure the 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= "Guo.examples.mq02.topic.TopicProvider" ><property name= " Topicjmstemplate " ref=" topicjmstemplate "></property></bean><!--  Message subject listeners   and   Subject monitoring container   can be configured with multiple Subscribers  --><!--  Message subject listener (Topic)  --><bean id= "Topicmessagelistener"  class= "Guo.examples.mq02.topic.TopicMessageListener  /><!--  Subject monitoring container   (Topic)  --><bean id= "Topicjmscontainer" class= " Org.springframework.jms.listener.DefaultMessageListenerContainer "><property name=" connectionfactory " ref=" ConnectionFactory " /><property name=" Destination " ref=" Topicdestination "  /><property name= "MessageListener"  ref= "Topicmessagelistener"  /></bean>

3.2 Message Publishers
package guo.examples.mq02.topic;import javax.jms.destination;import javax.jms.jmsexception; import javax.jms.message;import javax.jms.session;import  org.springframework.jms.core.jmstemplate;import org.springframework.jms.core.messagecreator;public  class topicprovider {private jmstemplate topicjmstemplate;/** *  publishing messages to the specified topic  *  *  @param  topic *  @param  msg */public void publish ( final destination topic, final string msg)  {topicjmstemplate.send (topic,  New messagecreator ()  {public message createmessage (session session)  throws  Jmsexception {system.out.println ("topic name " is " + topic.tostring () + ", the content of the publication message is: \ t " + msg"); Return session.createtextmessage (msg);});} Public void settopicjmstemplate (jmstemplate topicjmstemplate)  {this.topicjmstemplaTe = topicjmstemplate;}} 

3.3 Message subscribers (listening)
Package Guo.examples.mq02.topic;import Javax.jms.jmsexception;import Javax.jms.message;import Javax.jms.messagelistener;import javax.jms.textmessage;/** * is the same code as the queue listener. */public class Topicmessagelistener implements MessageListener {public void onMessage (Message message) {TextMessage TM = ( TextMessage) message;try {System.out.println ("Topicmessagelistener \ T" + tm.gettext ());} catch (JMSException e) { E.printstacktrace ();}}}


4. Testing4.1 Test Code
package guo.examples.mq02;import javax.jms.destination;import  guo.examples.mq02.queue.consumerservice;import guo.examples.mq02.queue.producerservice;import  Guo.examples.mq02.topic.topicprovider;import org.junit.test;import org.junit.runner.runwith;import  org.springframework.beans.factory.annotation.Autowired;import  org.springframework.beans.factory.annotation.qualifier;import  org.springframework.test.context.contextconfiguration;import  org.springframework.test.context.junit4.springjunit4classrunner;/** *  Test spring jms *   * 1. Test producer Send Message  *  * 2.  test consumer Accept Message  *  * 3.  test message Listener  *  * 4. Test Subject Monitor  * */@RunWith (springjunit4classrunner.class)//  Applicationcontext context = new// classpathxmlapplicationcontext ("ApplicationContext.xml" ); @ContextConfiguration ("/applicationcontext.xml") PUBLIC&NBSP;CLASS&NBSP;SPRINGJMStest {/** *  queue name queue1 */@Autowiredprivate  Destination queueDestination;/**  *  queue name queue2 */@Autowiredprivate  Destination queueDestination2;/** *  Theme  guo_ topic */@Autowired @qualifier ("Topicdestination") private destination topic;/** *  Topic message Publisher  */@Autowiredprivate  TopicProvider topicProvider;/** *  queue message producer  */@ Autowired@qualifier ("Producerservice") private producerservice producer;/** *  queue message producer   */@Autowired @qualifier ("Consumerservice") private consumerservice consumer;/** *  Test producer sends message to QUEUE1  */@Testpublic  void testproduce ()  {String msg =  "Hello  world! "; Producer.sendmessage (msg);} /** *  test consumers receive messages from Queue1  */@Testpublic  void testconsume ()  {consumer.receive ( queuedestination);} /** *  test Message Listener  *  * 1. The producer sends a message to the queue queue2  *  * 2. Consumermessagelistener listens to queues and consumes messages  */@Testpublic  void testsend ()  {producer.sendmessage ( queuedestination2,  "hello china~~~~~~~~~~~~~~~");} /** *  test Subject Monitor  *  * 1. The producer publishes a message  *  * 2 to the topic. Consumermessagelistener monitor the subject and consume the message  */@Testpublic  void testtopic ()  throws exception  {topicprovider.publish (topic,  "hello t-to-top-topi-topic!");}}

4.2 Test Results
Topic name is Topic://guo_topic, and the message content is: Hello t-to-top-topi-topic! Topicmessagelistener Hello t-to-top-topi-topic! sends a message to the queue queue://queue2------------Hello china~~~~~~~~~~~~~~~ Consumermessagelistener received a text message: Hello china~~~~~~~~~~~~~~~ sent a message to the queue queue://queue1------------Hello world! from queue ://queue1 received a message: Hello world!

5. Code Address

Http://pan.baidu.com/s/1sjymHlF

ACTIVEMQ Study Notes (v)--send and receive messages using spring JMS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.