摘要: 最近在项目开发中,需要用到activemq,用的时候,发现在同一个项目中point-to-point模式中,配置多个队列,消息生成者只能往一个队列中发消息或者往多个队列发送相同消息,并且监听器只能监听一个队列,这样配置多个队列也没有意义,作者想要实现的是:配置多个队列,并且生产者可以往多个队列中发送不同的消息,监听器消费时,可以判断根据不同的队列进行相应的业务处理,网上搜了一个,发现都是单个队列和监听,研究了一下,发现是可以实现的,废话不多说,直接上代码:
项目结构截图
maven所需依赖
- <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.gxf</groupId>
- <artifactId>springmq</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>springmq Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <!-- 版本管理 -->
- <properties>
- <springframework>4.1.8.RELEASE</springframework>
- <javax.servlet>3.1.0</javax.servlet>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.10</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>jstl</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>${javax.servlet}</version>
- </dependency>
- <!-- spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${springframework}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${springframework}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>${springframework}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${springframework}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jms</artifactId>
- <version>${springframework}</version>
- </dependency>
- <!-- xbean 如<amq:connectionFactory /> -->
- <dependency>
- <groupId>org.apache.xbean</groupId>
- <artifactId>xbean-spring</artifactId>
- <version>3.16</version>
- </dependency>
- <!-- activemq -->
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-core</artifactId>
- <version>5.7.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.activemq</groupId>
- <artifactId>activemq-pool</artifactId>
- <version>5.14.3</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>springmq</finalName>
- </build>
- </project>
-activemq配置文件:activemq.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:amq="http://activemq.apache.org/schema/core"
- xmlns:jms="http://www.springframework.org/schema/jms"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
- http://www.springframework.org/schema/jms
- http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
- http://activemq.apache.org/schema/core
- http://activemq.apache.org/schema/core/activemq-core-5.14.3.xsd"
- >
- <context:component-scan base-package="com.gxf" />
- <mvc:annotation-driven />
- <amq:connectionFactory id="amqConnectionFactory" brokerURL="tcp://192.168.0.112:61616" userName="admin" password="admin"></amq:connectionFactory>
- <!-- 配置JMS连接工长 -->
- <bean id="connectionFactory"
- class="org.springframework.jms.connection.CachingConnectionFactory">
- <constructor-arg ref="amqConnectionFactory" />
- <property name="sessionCacheSize" value="100" />
- </bean>
- <!-- 定义消息队列(Queue) -->
- <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
- <!-- 配置两个消息队列:queue1,queue2 -->
- <constructor-arg index="0" value="queue1,queue2" />
- </bean>
- <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
- <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
- <property name="connectionFactory" ref="connectionFactory" />
- <property name="defaultDestination" ref="queueDestination" />
- <property name="receiveTimeout" value="10000" />
- <!-- true是topic,false是queue,默认是false,此处显示写出false -->
- <property name="pubSubDomain" value="false" />
- </bean>
- <!-- 配置消息队列监听者(Queue) -->
- <bean id="queueMessageListener" class="com.gxf.listener.QueueMessageListener" />
- <bean id="queueListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
- <property name="connectionFactory" ref="connectionFactory" />
- <property name="destination" ref="queueDestination" />
- <property name="messageListener" ref="queueMessageListener" />
- </bean>
- </beans>
-springmvc配置文件:springmvc.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:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
- <context:component-scan base-package="com.gxf" />
- <mvc:annotation-driven />
- <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView" />
- <property name="prefix" value="/WEB-INF/views/" />
- <property name="suffix" value=".jsp" />
- </bean>
- </beans>
-Controll层 MainHandler.java代码:
- package com.gxf.handler;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import javax.annotation.Resource;
- import javax.jms.Destination;
- import org.apache.activemq.command.ActiveMQDestination;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.servlet.ModelAndView;
- import com.gxf.service.ProducerService;
- /**
- *
- * @author stark2017
- *
- */
- @Controller
- public class MainHandler {
- //队列名
- @Resource(name="queueDestination")
- private Destination queueDestination;
- //队列消息生产者
- @Resource(name="producerService")
- private ProducerService producerService;
- @RequestMapping(value="/main",method=RequestMethod.GET)
- public String producer(){
- return "main";
- }
- /**
- * 往队列queue1中发送消息
- * @param message
- * @return
- */
- @RequestMapping(value="/sendone",method=RequestMethod.POST)
- public String producer(@RequestParam("message") String message) {
- /**
- * 将destination强制转换为ActiveMQDestination,在ActiveMQDestination对象中,
- * 通过getCompositeDestinations()方法获取destination队列数组:queue://queue1 queue://queue2
- *
- */
- ActiveMQDestination activeMQDestination=(ActiveMQDestination) queueDestination;
- /**
- * 往队列queue1中发送文本消息
- */
- System.out.println("往队列"+activeMQDestination.getCompositeDestinations()[0].getPhysicalName()+"中发送文本消息");
- producerService.sendTxtMessage(activeMQDestination.getCompositeDestinations()[0], message);
- /**
- * 往队列queue1中发送MapMessage消息
- */
- System.out.println("往队列"+activeMQDestination.getCompositeDestinations()[0].getPhysicalName()+"中发送MapMessage消息");
- producerService.sendMapMessage(activeMQDestination.getCompositeDestinations()[0], message);
- //String bb="fdsalfkasdfkljasd;flkajsfd";
- //byte[] b = bb.getBytes();
- // producer.sendBytesMessage(demoQueueDestination, b);
- //producer.sendMapMessage(mqQueueDestination, message);
- return "main";
- }
- /**
- * 往消息队列queue2中发送消息
- * @param message
- * @return
- */
- @RequestMapping(value="/sendtwo",method=RequestMethod.POST)
- public String producertwo(@RequestParam("message") String message) {
- /**
- * 将destination强制转换为ActiveMQDestination,在ActiveMQDestination对象中,
- * 通过getCompositeDestinations()方法获取destination队列数组:queue://queue1 queue://queue2
- *
- */
- ActiveMQDestination activeMQDestination=(ActiveMQDestination) queueDestination;
- /**
- * 队列queue2中发送文本消息
- */
- System.out.println("往队列"+activeMQDestination.getCompositeDestinations()[1].getPhysicalName()+"中发送文本消息");
- producerService.sendTxtMessage(activeMQDestination.getCompositeDestinations()[1], message);
- /**
- * 队列queue2中发送mapMessage消息
- */
- System.out.println("往队列"+activeMQDestination.getCompositeDestinations()[1].getPhysicalName()+"中发送文本消息");
- producerService.sendMapMessage(activeMQDestination.getCompositeDestinations()[1], message);
- String bb="fdsalfkasdfkljasd;flkajsfd";
- byte[] b = bb.getBytes();
- // producer.sendBytesMessage(demoQueueDestination, b);
- //producer.sendMapMessage(mqQueueDestination, message);
- return "main";
- }
- }
-生产者ProducerService.java代码:
- package com.gxf.service;
- import java.io.Serializable;
- import java.util.List;
- import java.util.Map;
- import javax.annotation.Resource;
- import javax.jms.BytesMessage;
- import javax.jms.Destination;
- import javax.jms.JMSException;
- import javax.jms.MapMessage;
- import javax.jms.Message;
- import javax.jms.Session;
- import javax.jms.StreamMessage;
- import org.springframework.jms.core.JmsTemplate;
- import org.springframework.jms.core.MessageCreator;
- import org.springframework.stereotype.Service;
- @Service
- public class ProducerService {
- @Resource(name = "jmsTemplate")
- private JmsTemplate jmsTemplate;
- /**
- * 向指定Destination发送text消息
- *
- * @param destination
- * @param message
- */
- public void sendTxtMessage(Destination destination, final String message) {
- if (null == destination) {
- destination = jmsTemplate.getDefaultDestination();
- }
- jmsTemplate.send(destination, new MessageCreator() {
- public Message createMessage(Session session) throws JMSException {
- return session.createTextMessage(message);
- }
- });
- System.out.println("springJMS send text message...");
- }
- /**
- * 向指定Destination发送map消息
- *
- * @param destination
- * @param message
- */
- public void sendMapMessage(Destination destination, final String message) {
- if (null == destination) {
- destination = jmsTemplate.getDefaultDestination();
- }
- jmsTemplate.send(destination, new MessageCreator() {
- public Message createMessage(Session session) throws JMSException {
- MapMessage mapMessage = session.createMapMessage();
- mapMessage.setString("msgId", message);
- return mapMessage;
- }
- });
- System.out.println("springJMS send map message...");
- }
- /**
- * 向指定Destination发送序列化的对象
- *
- * @param destination
- * @param object
- * object 必须序列化
- */
- public void sendObjectMessage(Destination destination, final Serializable object) {
- if (null == destination) {
- destination = jmsTemplate.getDefaultDestination();
- }
- jmsTemplate.send(destination, new MessageCreator() {
- public Message createMessage(Session session) throws JMSException {
- return session.createObjectMessage(object);
- }
- });
- System.out.println("springJMS send object message...");
- }
- /**
- * 向指定Destination发送字节消息
- *
- * @param destination
- * @param bytes
- */
- public void sendBytesMessage(Destination destination, final byte[] bytes) {
- if (null == destination) {
- destination = jmsTemplate.getDefaultDestination();
- }
- jmsTemplate.send(destination, new MessageCreator() {
- public Message createMessage(Session session) throws JMSException {
- BytesMessage bytesMessage = session.createBytesMessage();
- bytesMessage.writeBytes(bytes);
- return bytesMessage;
- }
- });
- System.out.println("springJMS send bytes message...");
- }
- /**
- * 向默认队列发送Stream消息
- */
- public void sendStreamMessage(Destination destination) {
- jmsTemplate.send(new MessageCreator() {
- public Message createMessage(Session session) throws JMSException {
- StreamMessage message = session.createStreamMessage();
- message.writeString("stream string");
- message.writeInt(11111);
- return message;
- }
- });
- System.out.println("springJMS send Strem message...");
- }
- }
-队列消息监听器QueueMessageListener.java代码:
- package com.gxf.listener;
- import javax.jms.BytesMessage;
- import javax.jms.JMSException;
- import javax.jms.MapMessage;
- import javax.jms.Message;
- import javax.jms.MessageListener;
- import javax.jms.ObjectMessage;
- import javax.jms.StreamMessage;
- import javax.jms.TextMessage;
- import org.apache.activemq.advisory.DestinationEvent;
- import org.apache.activemq.command.ActiveMQDestination;
- import org.apache.activemq.command.ActiveMQMessage;
- import org.apache.activemq.command.DestinationInfo;
- public class QueueMessageListener implements MessageListener {
- //当收到消息后,自动调用该方法
- @Override
- public void onMessage(Message message) {
- try {
- ActiveMQDestination queues=(ActiveMQDestination)message.getJMSDestination();
- /**
- * 监听消息队列queue1中的消息
- */
- if(queues.getPhysicalName().equalsIgnoreCase("queue1"))
- {
- System.out.println("监听队列:"+queues.getPhysicalName()+"消费了消息:");
- // 如果是文本消息
- if (message instanceof TextMessage) {
- TextMessage tm = (TextMessage) message;
- try {
- System.out.println("from get textMessage:\t" + tm.getText());
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // 如果是Map消息
- if (message instanceof MapMessage) {
- MapMessage mm = (MapMessage) message;
- try {
- System.out.println("from get MapMessage:\t" + mm.getString("msgId"));
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- /**
- * 监听消息队列queue2中的消息
- */
- if(queues.getPhysicalName().equalsIgnoreCase("queue2"))
- {
- System.out.println("监听队列:"+queues.getPhysicalName()+"消费了消息:");
- // 如果是文本消息
- if (message instanceof TextMessage) {
- TextMessage tm = (TextMessage) message;
- try {
- System.out.println("from get textMessage:\t" + tm.getText());
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // 如果是Map消息
- if (message instanceof MapMessage) {
- MapMessage mm = (MapMessage) message;
- try {
- System.out.println("from get MapMessage:\t" + mm.getString("msgId"));
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- } catch (JMSException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- // 如果是Object消息
- if (message instanceof ObjectMessage) {
- ObjectMessage om = (ObjectMessage) message;
- System.out.println("from get ObjectMessage:\t");
- }
- // 如果是bytes消息
- if (message instanceof BytesMessage) {
- System.out.println("from get BytesMessage:\t");
- byte[] b = new byte[1024];
- int len = -1;
- BytesMessage bm = (BytesMessage) message;
- try {
- while ((len = bm.readBytes(b)) != -1) {
- System.out.println(new String(b, 0, len));
- }
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // 如果是Stream消息
- if (message instanceof StreamMessage) {
- System.out.println("from get BytesMessage:\t");
- StreamMessage sm = (StreamMessage) message;
- try {
- System.out.println(sm.readString());
- System.out.println(sm.readInt());
- } catch (JMSException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }}
- }
-启动项目访问main,进行消息发送:
后台打印往不同队列发送的消息和监听到不同队列中的消息:
队列queue1发送消费了14条消息,queue2发送消费了10条消息:
到此想要的功能需求已实现
文章来源:https://my.oschina.net/u/3613230/blog/1457227