spring+activemq实战之配置监听多队列实现不同队列消息消费
摘选:https://my.oschina.net/u/3613230/blog/1457227
摘要: 最近在项目开发中,需要用到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.</modelVersion>
<groupId>com.gxf</groupId>
<artifactId>springmq</artifactId>
<packaging>war</packaging>
<version>0.0.-SNAPSHOT</version>
<name>springmq Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 版本管理 -->
<properties>
<springframework>4.1..RELEASE</springframework>
<javax.servlet>3.1.</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.</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.14.</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条消息:
到此想要的功能需求已实现
spring+activemq实战之配置监听多队列实现不同队列消息消费的更多相关文章
- ActiveMQ学习总结(10)——ActiveMQ采用Spring注解方式发送和监听
对于ActiveMQ消息的发送,原声的api操作繁琐,而且如果不进行二次封装,打开关闭会话以及各种创建操作也是够够的了.那么,Spring提供了一个很方便的去收发消息的框架,spring jms.整合 ...
- spring中配置监听队列的MQ
一.spring中配置监听队列的MQ相关信息注:${}是读取propertites文件的常量,这里忽略.绿色部分配置在接收和发送端都要配置. <bean id="axx" ...
- spring +ActiveMQ 实战 topic selecter指定接收
spring +ActiveMQ 实战 topic selecter指定接收 queue:点对点模式,一个消息只能由一个消费者接受 topic:一对多,发布/订阅模式,需要消费者都在线(可能会导致信息 ...
- Spring session(redis存储方式)监听导致创建大量redisMessageListenerContailner-X线程
待解决的问题 Spring session(redis存储方式)监听导致创建大量redisMessageListenerContailner-X线程 解决办法 为spring session添加spr ...
- Sprinboot优雅配置监听,并记录所有启动事件
在阅读Springboot启动源码的时候,发现Springboot自动启动listeners是通过uopeizhi文件配置的,本文就是采用Springboot方式自动装入listeners. 项目依赖 ...
- oracle 11g 服务启动时提示1053错误,服务启动不了,重新配置监听解决问题
早上发现oracle服务启动不了了,找了很多资料,没找到有用的.通过重新配置监听解决问题.
- 新建Oracle数据库时,提示使用database control配置数据库时,要求在当前oracle主目录中配置监听程序
新建一个oracle数据库时,当提示使用database control配置数据库时,要求在当前oracle主目录中配置监听程序等字样的时候,问题是那个监听的服务没有启动,解决方法如下: 打开cmd命 ...
- 涂抹Oracle笔记1-创建数据库及配置监听程序
一.安装ORACLE数据库软件及创建实例OLTP:online transaction processing 指那些短事务,高并发,读写频繁的数据库系统.--DB_BLOCK_SIZE通常设置较小.O ...
- [Java聊天室server]实战之二 监听类
前言 学习不论什么一个稍有难度的技术,要对其有充分理性的分析,之后果断做出决定---->也就是人们常说的"多谋善断":本系列尽管涉及的是socket相关的知识,但学习之前,更 ...
随机推荐
- python容器类型集合的操作
集合(set):集合是一个无序的序列,集合中的元素可以是任意数据类型:表现形式是set(集合的元素),能够实现自动去重:集合传入的必须是一个hashable类型值,(不能存储字典格式的值):并且创建集 ...
- Discovery and auto register
1.Discovery 2. auto register 2.1 agent 端配置 2.2 server 端配置
- 阿里云:uwsgi--配置出错 bind(): Address already in use [core/socket.c line 769]
按照网上配置nginx+uwsgi+django的文章,nginx启动成功,django启动也成功,单独用uwsgi --http :8000 命令启动uwsgi也成功.使用uwsgi --sock ...
- JAVA中快速生成get与set
快捷键 ctrl+Alt+S generate getters and setters
- jvm垃圾回收器与内存分配策略
一.判断对象存活的算法 1.引用计数算法 (1)概念:给对象中添加一个引用计数器每当有一个地方引用它时,计数器值加1:当引用失效时,计数器就减1:任何时刻计数器为0的对象就是不可能再被使用的. (2) ...
- Android PhotoView基本功能实现
Android开发过程中,想必都使用过PhotoView来实现图片展示的功能.在最新版的sdk(android-23)有了一个原生的photoView,并且代码实现也很简单,逻辑也很清晰.我们在实际的 ...
- 42步进阶学习—让你成为优秀的Java大数据科学家!
作者 灯塔大数据 本文转自公众号灯塔大数据(DTbigdata),转载需授权 如果你对各种数据类的科学课题感兴趣,你就来对地方了.本文将给大家介绍让你成为优秀数据科学家的42个步骤.深入掌握数据准备, ...
- block的本质
全局变量
- php踩过的那些坑(3) 数据类型转换
一.前方有坑 php属于弱类型语言,不会强迫工程师在使用变量之前先声明变量类型,开发时爽了,但是也带来不少的坑.下面就举一个坑的例子: 例1: $str = ‘haodaquan'; echo ($s ...
- element table 先显示暂无数据 之后再加载数据 问题
项目中的表格请求数据时,进去页面,先出现 ''暂无数据'' 字样闪现一下之后在进行加载数据,用户体验十分不好 解决办法: <template> <el-table :data=&qu ...