Quote:

Recently, the company has made a project focusing on information security, and one of the business requirements is that the project regularly monitors the behavior of users. For some serious violations, email alarms are sent in the form of FoxMail, which may be multiple or one person. For the first time, it is in the form of one person. , directly in the business layer need to send mail to alarm, but behind requirements change, for some warning E-mail may send people, which may have blocked mail, until all the E-mail is sent and then continue to do business, at the bottom of the leader says it will affect the user experience, E-mail users have been waiting, You can’t do anything else. Finally, the study said that with message queue, when there is a need to send an email alarm, an identification message is added to the queue. ActiveMQ monitors the hours in the queue in real time in the form of listeners. After receiving the message, it determines whether the identification of the alarm needs to be sent. This is the study of message queue ActiveMQ, the following is the specific content:

A, ActiveMQ

1.1). ActiveMQ

ActiveMQ is an open source Message system provided by Apache, which is completely implemented by Java. Therefore, it can well support JMS (Java Message Service) specification proposed by J2EE. JMS is a set of Java application interfaces that provide services for message creation, sending, reading, and so on. JMS provides a common set of application programming interfaces and response syntax, similar to JDBC, the unified access interface for Java databases. It is a vendor-neutral API that enables Java programs to communicate well with message components from different vendors.

1. 2). Java Message Service(JMS)

JMS supports two message sending and receiving models.

  • One is called P2P(Ponit to Point) model (point-to-point), which uses point-to-point mode to send messages. P2P model is based on the queue, the message producer sends the message to the queue, the message consumer receives the message from the queue, the existence of the queue makes the asynchronous transmission of the message is called possible, P2P model in the case of point-to-point messaging.

  • The other is called Pub/Sub(Publish/Subscribe) model, which defines how to Publish and Subscribe messages to a content node called topic. Topics can be thought of as intermediaries for message delivery, with message publishing publishing messages to a topic from which message subscribers subscribe. Topic makes the subscriber of message and the publisher of message keep each other independent, do not need to contact to ensure the transmission of message, publish-subscribe model is adopted in the one-to-many broadcast of message.

1.3). JMS terminology

  1. Provider/MessageProvider: indicates the producer
  2. Consumer/MessageConsumer: Consumer
  3. PTP: Point-to-point communication message model
  4. Pub/Sub: Publish/Subscribe, Publish Subscribe message model
  5. Queue: Queue, one of the target types, combined with PTP
  6. Topic: Topic, one of the target types, combined with Pub/Sub
  7. ConnectionFactory: the ConnectionFactory that JMS uses to create connections
  8. Connnection: connection between the JMS Client and the JMS Provider
  9. Destination: Message Destination, created by Session
  10. Session: a Session, created by a Connection, is essentially a thread that sends and receives messages. Therefore, producers and consumers are created in Session

1.4). ActiveMQ application scenario

Similar to sending express goods, the producer sends the Message to a specified destination and then can leave. After receiving the notification, the customer can go to the destination to get the Message. Of course, the delivery may be authenticated, which involves specifying a username and password when creating a connection. What’s more, in real life, when the Courier places the express, it is supposed to inform the customer where to pick up the express, while ActiveMq helps us do everything. ActiveMq will help us realize the notification work, without us personally coding to inform the consumer, the producer just needs to put the Message into Mq. Mq will take care of that for us

The purpose is to process messages, that is, to process JMS in large e-commerce websites, such as JINGdong, Taobao, go where and other websites have in-depth application, the main role of the queue is to eliminate high concurrent access peak, speed up the response speed of the website.

In the case of no message queue, the user’s request data is directly written to the database. In the case of high frequency, the database will be under great pressure and the system response delay will be aggravated. However, after the use of queue, the user’s request is sent to the queue and immediately returned.

1.5). ActiveMQ download

1.6.)

/ apache activemq – 5.15.3 / bin/win64 / directory. Double-click the activemq bat file, enter http://localhost:8161/admin/ in the browser, the admin user name and password entered

Srping+ActiveMQ application example

2,1). Project structure

** 2,2). Import maven dependencies,pom.xml file **

1 <? xml version="1.0" encoding="UTF-8"? > 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 < modelVersion > 4.0.0 < / modelVersion > 5 6 < groupId > www.cnblogs.com.hongmoshu < / groupId > 7 <artifactId> test_actMQ </artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 <packaging> WAR </ Packaging > 10 <name> test_actMQ  Maven Webapp</name> 11 <url>http://www.example.com</url> 12 13 <! RELEASE</ springFramework > 16 </ springFramework > 16 </properties> 17 18 19 <dependencies> 20 21 <! --> 22 <dependency> 23 <groupId>junit</groupId> 24 <artifactId>junit</artifactId> 25 26 < < version > 4.11 < / version > scope >test</scope> 27 </dependency> 28 29 <! -- JSP related --> 30 <dependency> 31 <groupId> JSTL </groupId> 32 <artifactId> JSTL </artifactId> 33 <version>1.2</version> 34 </dependency> 35 <dependency> 36 <groupId>javax.servlet</groupId> 37 <artifactId>servlet-api</artifactId> 38 <scope> Provided </scope> 39 <version>2.5</version> 40 </dependency> 41 42 <! -- spring --> 43 <dependency> 44 <groupId>org.springframework</groupId> 45 <artifactId>spring-core</artifactId> 46 <version>${springframework}</version>
 47     </dependency>
 48     <dependency>
 49       <groupId>org.springframework</groupId>
 50       <artifactId>spring-context</artifactId>
 51       <version>${springframework}</version>
 52     </dependency>
 53     <dependency>
 54       <groupId>org.springframework</groupId>
 55       <artifactId>spring-tx</artifactId>
 56       <version>${springframework}</version>
 57     </dependency>
 58     <dependency>
 59       <groupId>org.springframework</groupId>
 60       <artifactId>spring-webmvc</artifactId>
 61       <version>${springframework}</version>
 62     </dependency>
 63     <dependency>
 64       <groupId>org.springframework</groupId>
 65       <artifactId>spring-jms</artifactId>
 66       <version>${springframework}</version> 67 </dependency> 68 69 <! -- Xbean <amq:connectionFactory /> --> 70 <dependency> 71 <groupId>org.apache.xbean</groupId> 72 <artifactId>xbean-spring</artifactId> 73 <version>3.16</version> 74 </dependency> 75 76 <! -- activemq --> 77 <dependency> 78 <groupId>org.apache.activemq</groupId> 79 <artifactId>activemq-core</artifactId> 80 <version>5.7.0</version> 81 </dependency> 82 <dependency> 83 <groupId>org.apache.activemq</groupId> 84 <artifactId> Activemq -pool</artifactId> 85 <version>5.12.1</version> 86 </dependency> 87 88 <! -- gson --> 89 <dependency> 90 <groupId>com.google.code.gson</groupId> 91 <artifactId>gson</artifactId> 92 <version>1.7.1</version> 93 </dependency> 94 95 <! -- JSON --> 96 <dependency> 97 <groupId>net.sf.json-lib</groupId> 98 <artifactId>json-lib</artifactId> 99 <version>2.4</version> 100 <classifier>jdk15</classifier> 101 </dependency> 102 103 </dependencies> 104 105 <build> 106 <finalName>test_actmq</finalName> 107 108 </build> 109 </project>Copy the code

2,3). ActiveMQ configuration file activemq.xml

1 <? xml version="1.0" encoding="UTF-8"? > 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:amq="http://activemq.apache.org/schema/core"
 5        xmlns:jms="http://www.springframework.org/schema/jms"
 6        xmlns:context="http://www.springframework.org/schema/context"
 7        xmlns:mvc="http://www.springframework.org/schema/mvc"
 8        xsi:schemaLocation="9 10 11 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/beans 12 13 http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 14 15 16 17 http://www.springframework.org/schema/jms/spring-jms-4.1.xsd http://www.springframework.org/schema/jms http://activemq.apache.org/schema/core and http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"
19 >
20 
21     <context:component-scan base-package="com.svse.service"/> 22 <mvc:annotation-driven /> 23 24 <! -- jms.useAsyncSend=trueAllow asynchronous message receiving --> 25 < AMQ :connectionFactory ID ="amqConnectionFactory"
26                            brokerURL="TCP: / / 192.168.6.111:61616? jms.useAsyncSend=true"
27                            userName="admin"
28                            password="admin"29 30 / > <! -- Configure JMS connection factory --> 31 <bean id="connectionFactory"
32           class="org.springframework.jms.connection.CachingConnectionFactory">
33         <constructor-arg ref="amqConnectionFactory" />
34         <property name="sessionCacheSize" value="100"/> 35 </bean> 36 37 <! -- Define message Queue name --> 38 <bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue"> and <! > 40 <constructor-arg> 41 <value>Jaycekon</value> 42 </constructor-arg> 43 </bean> 44 45 <! -- Configure JMS templates (Queue), JMS utility classes provided by Spring, which send and receive messages. --> 46 <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
47         <property name="connectionFactory" ref="connectionFactory" />
48         <property name="defaultDestination" ref="demoQueueDestination" />
49         <property name="receiveTimeout" value="10000"/ > < 50! --trueIs the topic,falseIt's queue. The default is queuefalse, displays writefalse -->
51         <property name="pubSubDomain" value="false"52 / > <! -- Message converter --> 53 <property name="messageConverter" ref="userMessageConverter"/> 54 </bean> 55 56 <! Type converter --> 57 <bean id="userMessageConverter" class="com.svse.util.ObjectMessageConverter"/> 58 59 60 <! Message Queue listener --> 61 <bean id="queueMessageListener" class="com.svse.util.QueueMessageListener"/ > 62 < 63! -- Display the injected message listener (Queue), configure the connection factory, listen to the demoQueueDestination, listener is defined above --> 64 <bean id="queueListenerContainer"
65           class="org.springframework.jms.listener.DefaultMessageListenerContainer">
66         <property name="connectionFactory" ref="connectionFactory" />
67         <property name="destination" ref="demoQueueDestination" />
68         <property name="messageListener" ref="queueMessageListener" />
69     </bean> 
70     
71 </beans>
Copy the code

2,4). Spring configuration file spring-mvc.xml

1 <? xml version="1.0" encoding="UTF-8"? > 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 9 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 10 http://www.springframework.org/schema/mvc and http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
12          
13     <context:component-scan base-package="com.svse.controller" />
14     <mvc:annotation-driven />
15     <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
16         <property name="viewClass"
17             value="org.springframework.web.servlet.view.JstlView" />
18         <property name="prefix" value="/WEB-INF/views/" />
19         <property name="suffix" value=".jsp" />
20     </bean>
21      
22 </beans>
Copy the code

2, 5). Web. XML

1 <? xml version="1.0" encoding="UTF-8"? > 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 3          xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
 5          id="WebApp_ID" version="3.1"> 6 <display-name>mydemo</display-name> 7 8 <welcome-file-list> 9 <welcome-file>index.jsp</welcome-file> 10 </welcome-file-list> 11 12 <! Load spring and active configuration files. Classpath is the path under project SRC --> 13 <context-param> 14 <param-name>contextConfigLocation</param-name> 15 <param-value> 16 classpath:spring-mvc.xml; 17 classpath:ActiveMQ.xml; 18 </param-value> 19 </context-param> 20 21 22 <listener> 23 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 24 </listener> 25 26 <servlet> 27  <servlet-name>springMVC</servlet-name> 28 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 29 <init-param> 30 <param-name>contextConfigLocation</param-name> 31 <param-value>classpath:spring-mvc.xml</param-value> 32 </init-param> 33 <load-on-startup>1</load-on-startup> 34 </servlet> 35 <servlet-mapping> 36 <servlet-name>springMVC</servlet-name> 37 <url-pattern>/</url-pattern> 38 </servlet-mapping> 39 40 <! <filter> 42 <filter-name>characterEncodingFilter</filter-name> 43 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 44 <init-param> 45 <param-name>encoding</param-name> 46 <param-value>UTF-8</param-value> 47 </init-param> 48 <init-param> 49 <param-name>forceEncoding</param-name> 50 <param-value>true</param-value>
51     </init-param>
52   </filter>
53   <filter-mapping>
54     <filter-name>characterEncodingFilter</filter-name>
55     <url-pattern>/*</url-pattern>
56   </filter-mapping>
57   
58 </web-app>
Copy the code

2,6). Entity class Users objects

 1 package com.svse.entity;
 2 import java.io.Serializable;
 3 
 4 public class Users implements Serializable{
 5 
 6     private String userId;
 7     private String userName;
 8     private String sex;
 9     private String age;
10     private String type;
11     
12     
13     public Users() {
14         super();
15     }
16     public Users(String userId, String userName, String sex, String age,
17             String type) {
18         super();
19         this.userId = userId;
20         this.userName = userName;
21         this.sex = sex;
22         this.age = age;
23         this.type = type;
24     }
25     public String getUserId() {26return userId;
27     }
28     public void setUserId(String userId) {
29         this.userId = userId;
30     }
31     public String getUserName() {32return userName;
33     }
34     public void setUserName(String userName) {
35         this.userName = userName;
36     }
37     public String getSex() {38return sex;
39     }
40     public void setSex(String sex) {
41         this.sex = sex;
42     }
43     public String getAge() {44return age;
45     }
46     public void setAge(String age) {
47         this.age = age;
48     }
49     public String getType() {50return type;
51     }
52     public void setType(String type) {
53         this.type = type;
54     }
55     @Override
56     public String toString() {57return "Users [userId=" + userId + ", userName=" + userName + ", sex="
58                 + sex + ", age=" + age + ", type=" + type + "]"; 59} 60 61 62}Copy the code

2,7). Core code (producer ProducerService)

 1 package com.svse.service;
 2 
 3 import javax.annotation.Resource;
 4 import javax.jms.Destination;
 5 import javax.jms.JMSException;
 6 import javax.jms.Message;
 7 import javax.jms.Session;
 8 
 9 import org.springframework.jms.core.JmsTemplate;
10 import org.springframework.jms.core.MessageCreator;
11 import org.springframework.stereotype.Service;
12 
13 import com.svse.entity.Users;
14 
15 @Service
16 public class ProducerService {
17 
18     @Resource(name="jmsTemplate") 19 private JmsTemplate jmsTemplate; 20 21 22 /** 23 * Sends messages to the specified queue (sending text messages) 24 */ 25 Public void sendMessage(Destination Destination,final String MSG){26 27 jmsTemplate.setDeliveryPersistent(true);
28         
29         System.out.println(Thread.currentThread().getName()+"To queue"+destination.toString()+"Send a message ---------------------->"+msg);
30         jmsTemplate.send(destination, new MessageCreator() {
31             public Message createMessage(Session session) throws JMSException {
32                 returnsession.createTextMessage(msg); 33}}); 39 */ 40 Public void sendMessageNew(Destination Destination,Users user){41 39 */ 40 Public void sendMessageNew(Destination Destination,Users user){41  System.out.println(Thread.currentThread().getName()+"To queue"+destination.toString()+"Send a message ---------------------->"+user); 42 jmsTemplate.convertAndSend(user); 43} 44 45 /** 46 * Sends a message to the default queue 47 */ 48 public void sendMessage(final String MSG){49 String destination = jmsTemplate.getDefaultDestinationName(); 50 System.out.println(Thread.currentThread().getName()+"To queue"+destination+"Send a message ---------------------->"+msg);
51         jmsTemplate.send(new MessageCreator() {
52             public Message createMessage(Session session) throws JMSException {
53                 returnsession.createTextMessage(msg); 54}} 55); 56}} 57Copy the code

2,8). Core code (ConsumerService)

 1 package com.svse.service;
 2 
 3 import javax.annotation.Resource;
 4 import javax.jms.Destination;
 5 import javax.jms.JMSException;
 6 import javax.jms.ObjectMessage;
 7 import javax.jms.TextMessage;
 8 
 9 import net.sf.json.JSONObject;
10 
11 import org.springframework.jms.core.JmsTemplate;
12 import org.springframework.stereotype.Service;
13 
14 import com.svse.entity.Users;
15 
16 @Service
17 public class ConsumerService {
18 
19      @Resource(name="jmsTemplate") 20 private JmsTemplate jmsTemplate; 22 public TextMessage Receive (Destination Destination){23 TextMessage TextMessage = (TextMessage) jmsTemplate.receive(destination); 24 try{ 25 JSONObject json=JSONObject.fromObject(textMessage.getText()); 26 System.out.println("name:"+json.getString("userName"));
27                 System.out.println(From the queue + destination.toString() + "Message received: \t"28 + textMessage.getText()); 29 } catch (JMSException e) { 30 e.printStackTrace(); 31} 32returntextMessage; Public ObjectMessage receiveNew(Destination Destination){36 ObjectMessage objMsg=(ObjectMessage) jmsTemplate.receive(destination); 38 try{ 39 Users users= (Users) objMsg.getObject(); 44 System.out.println("name:"+users.getUserName());
47                 System.out.println(From the queue + destination.toString() + "Message received: \t"48 + users); 49 } catch (JMSException e) { 50 e.printStackTrace(); 51} 52returnobjMsg; 53}} 54Copy the code

2,9). Core code (controller ConsumerService)

1 package com.svse.controller.mq; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 7 import javax.annotation.Resource; 8 import javax.jms.DeliveryMode; 9 import javax.jms.Destination; 10 import javax.jms.JMSException; 11 import javax.jms.ObjectMessage; 12 import javax.jms.TextMessage; 13 import javax.management.MBeanServerConnection; 14 import javax.management.remote.JMXConnector; 15 import javax.management.remote.JMXConnectorFactory; 16 import javax.management.remote.JMXServiceURL; 18 import org.springframework.stereotype.Controller; 19 import org.springframework.web.bind.annotation.RequestMapping; 20 import org.springframework.web.bind.annotation.RequestMethod; 21 import org.springframework.web.bind.annotation.RequestParam; 22 import org.springframework.web.servlet.ModelAndView; 24 import com.google.gson.Gson; 25 import com.svse.entity.Users; 26 import com.svse.service.ConsumerService; 27 import com.svse.service.ProducerService; 28 29 @controller 30 public class DemoController {35 36 @resource (name="demoQueueDestination") 38 private Destination demoQueueDestination; 39 40 Queue message producer 41 @resource (name="producerService") 42 private ProducerService producer; 43 44 // Queue message consumer 45 @Resource(name="consumerService") 46 private ConsumerService consumer; 47 48 /* 49 * Ready to send a message 50 */ 51 @requestMapping (value="/producer",method=RequestMethod.GET)
 52     public ModelAndView producer(){
 53         System.out.println("------------go producer");
 54         
 55         Date now = new Date(); 
 56         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 57         String time = dateFormat.format( now ); 
 58         System.out.println(time);
 59         
 60         ModelAndView mv = new ModelAndView();
 61         mv.addObject("time", time);
 62         mv.setViewName("producer");        
 63         returnmv; 64 */ 69 @requestMapping (value= value"/onsend",method=RequestMethod.POST)
 70     public ModelAndView producer(@RequestParam("message") String message) {
 71         System.out.println("------------send to jms");
 72         ModelAndView mv = new ModelAndView();
 73         for(int i=0; i<5; i++){ 74 try { 75 Users users=new Users("10"+(i+1),"Zhao Yuanyuan"+(i+1),"Female"."27"."Movie actor");
 76                 Gson gson=new Gson();
 77                 String sendMessage=gson.toJson(users);
 78                 System.out.println("Sent message sendMessage:"+sendMessage.toString()); 79 // producer.sendMessage(demoQueueDestination,sendMessage.toString()); // In the form of text 80 producer.sendMessageNew(demoQueueDestination, users); 81 82} catch (Exception e) {83 e.printStackTrace(); 84 } 85 } 86 mv.setViewName("index");
 87         returnmv; 91 */ 92 @requestMapping (value= value"/receive",method=RequestMethod.GET)
 93     public ModelAndView queue_receive() throws JMSException {
 94         System.out.println("------------receive message"); 95 ModelAndView mv = new ModelAndView(); 96 97 //TextMessage tm = consumer.receive(demoQueueDestination); 98 99 ObjectMessage objMsg= consumer.receivenew (demoQueueDestination); 100 Users Users = (Users) objmsg.getobject (); 101 //mv.addObject("textMessage", tm.getText());
102         mv.addObject("textMessage", users.getUserId()+"| |"+users.getUserName());
103         mv.setViewName("receive");
104         return mv;
105     }
106     
107     /*
108      * ActiveMQ Manager Test
109      */
110     @RequestMapping(value="/jms",method=RequestMethod.GET)
111     public ModelAndView jmsManager() throws IOException {
112         System.out.println("------------jms manager");
113         ModelAndView mv = new ModelAndView();
114         mv.setViewName("index");
115         
116         JMXServiceURL url = new JMXServiceURL(""); 117 JMXConnector connector = JMXConnectorFactory.connect(url); 118 connector.connect(); 119 MBeanServerConnection connection = connector.getMBeanServerConnection(); 120, 121,returnmv; 122} 123 124}Copy the code

Object converter MessageConverter and MessageListener MessageListener

In ProducerService and ConsumerService, you can either send or receive a message as a TextMessage or as an ObjectMessage. If it is a simple TextMessage, it can be sent as a TextMessage. However, if there is a lot of content to be sent and the structure is complex, it is recommended to send the message in the way of object text ObjectMessage to the queue. But this is where the object MessageConverter MessageConverter comes in.

3,1). Message converter MessageageConverte

MessageConverter has two main functions. On the one hand, it can transform our non-standardized Message object into our target Message object, which is mainly used for sending messages. On the other hand, it can convert our Message object to the corresponding target object, which is mainly used when receiving messages.

1 package com.svse.util; 2 3 import java.io.Serializable; 4 5 import javax.jms.JMSException; 6 import javax.jms.Message; 7 import javax.jms.ObjectMessage; 8 import javax.jms.Session; 9 10 import org.springframework.jms.support.converter.MessageConversionException; 11 import org.springframework.jms.support.converter.MessageConverter; 12 13 /** 14 * Function description: Generic message object conversion class 15 *@author: ZSQ 16 * CREATE Date: July 12, 2019 9:28:31 am 17 * Modifier Modified At Modified Description 18 *Copyright 19 */ 20 Public Class Implements MessageConverter {21 22 23 23 // Convert a Java Object to the corresponding JMS Message(when producing a Message) Session session) 25 throws JMSException, MessageConversionException { 26 27returnsession.createObjectMessage((Serializable) object); 31 Public Object fromMessage(Message Message) throws JMSException, 32 MessageConversionException { 33 ObjectMessage objMessage = (ObjectMessage) message; 34returnobjMessage.getObject(); 35} 36 37}Copy the code

Note: After writing the message converter, you also need to configure it in activemq.xml

3,2). Message listener MessageageListe

MessageageListe is used to dynamically listen to messages sent by the producer of the message queue, without manual receiving!

1 package com.svse.util; 2 import javax.jms.JMSException; 3 import javax.jms.Message; 4 import javax.jms.MessageListener; 5 import javax.jms.ObjectMessage; 6 import javax.jms.TextMessage; 7 8 import com.svse.entity.Users; 9 10 11 public class QueueMessageListener implements MessageListener { 12 13 Public void onMessage(Message Message) {15 public void onMessage(Message Message) {15 public void onMessage(Message Message) {15 public void onMessage(Message Message) {15 public void onMessage(Message Message)  //TextMessage tm = (TextMessage) message; 19 ObjectMessage objMsg=(ObjectMessage) message; 20 Users users; 21 try { 22 users = (Users) objMsg.getObject(); 23 //System.out.println("QueueMessageListener listens on text message: \t" + tm.getText());
24             System.out.println("QueueMessageListener listens on text message: \t"+ users); 25 / /dosomething ... 26 } catch (JMSException e1) { 27 // TODO Auto-generated catch block 28 e1.printStackTrace(); 29} 30} 31 32}Copy the code

After writing the listener, it is also necessary to register the configuration in Activemq.xml

conclusion

(1) When registering JmsTemplate, pay special attention to the value of the pubSubDomain attribute. The default is false, which means that the queue mode is supported, not the topic mode. However, if it is set to true, queue mode is not supported. Therefore, if the project needs to support both queue and Topic patterns, two JMStemPlates need to be registered, as well as two listener containers

(2) With Queue, producers can simply send messages to the MQ server and consumers can consume without the producer program running all the time;

(3) Messages are in first-in, first-out order and are removed from the MQ server queue once consumed by a consumer;

(4) the article says, “producers” < — – > “consumer” is a one-to-one relationship, actually is not accurate, can be seen from the application, a producer of news, can be more consumer spending, but many consumers in the consumer news is the relationship between competition, first get the first consumption, once the consumer is complete, the message will be out of the queue, It cannot be consumed again by other consumers, namely “one-time consumption”. The familiar “point-to-point” communication;