消息中间件activemq-5.13.0整合spring
首先说明这里是在qctivemq配置好并启动服务的情况下进行,请先自行配置好。也可关注我的博文(消息中间件qctivemq安全验证配置)进行配置。
1.首先看一下项目结构
2.所需jar包,这里只列出mq相关jar包,spring相关不与说明。
3.消息生产service QueueMessageProducer
package cn.carowl.activemq; 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; /**
* 消息生产者service
* @author weishengbin
*
*/
public class QueueMessageProducer {
private JmsTemplate jmsTemplate;
private Destination notifyQueue;
private NotifyMessageConverter messageConverter; public void sendQueue(String noticeInfo) {
sendMessage(noticeInfo);
} private void sendMessage(final String noticeInfo) {
this.jmsTemplate.send(notifyQueue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createObjectMessage(noticeInfo);
} });
} public JmsTemplate getJmsTemplate() {
return jmsTemplate;
} public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
} public Destination getNotifyQueue() {
return notifyQueue;
} public void setNotifyQueue(Destination notifyQueue) {
this.notifyQueue = notifyQueue;
} public NotifyMessageConverter getMessageConverter() {
return messageConverter;
} public void setMessageConverter(NotifyMessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
}
4.消息转换NotifyMessageConverter
package cn.carowl.activemq; import java.io.Serializable; import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session; import org.apache.activemq.command.ActiveMQObjectMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter; /**
* 消息转换
* @author weishengbin
*
*/
public class NotifyMessageConverter implements MessageConverter {
private static Logger logger = LoggerFactory.getLogger(NotifyMessageConverter.class); /**
* 转换NoticeInfo对象到消息
*/
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
System.out.println("sendMessage:"+object.toString());
ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
msg.setObject((Serializable) object);
return msg;
} /**
* 转换接收到的消息为NoticeInfo对象
*/
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
if (logger.isDebugEnabled()) {
logger.debug("Receive JMS message :" + message);
}
if (message instanceof ObjectMessage) {
ObjectMessage oMsg = (ObjectMessage) message;
if (oMsg instanceof ActiveMQObjectMessage) {
ActiveMQObjectMessage aMsg = (ActiveMQObjectMessage) oMsg;
try {
Object object = aMsg.getObject();
String noticeInfo = object.toString();
return noticeInfo;
} catch (Exception e) {
logger.error("Message:${} is not a instance of NoticeInfo." + message.toString());
throw new JMSException(
"Message:" + message.toString() + "is not a instance of NoticeInfo." + message.toString());
}
} else {
logger.error("Message:${} is not a instance of ActiveMQObjectMessage." + message.toString());
throw new JMSException("Message:" + message.toString() + "is not a instance of ActiveMQObjectMessage."
+ message.toString());
}
} else {
logger.error("Message:${} is not a instance of ObjectMessage." + message.toString());
throw new JMSException(
"Message:" + message.toString() + "is not a instance of ObjectMessage." + message.toString());
}
}
}
5.监听接收消息QueueMessageListener
package cn.carowl.activemq; import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 监听接收消息
* @author weishengbin
*
*/
public class QueueMessageListener implements MessageListener {
private static Logger logger = LoggerFactory.getLogger(QueueMessageListener.class);
private NotifyMessageConverter messageConverter; /**
* 接收消息
*/
public void onMessage(Message message) { try { ObjectMessage textMessage = (ObjectMessage) message;
String str = (String)messageConverter.fromMessage(textMessage);
System.out.println("接收到的消息:"+str); } catch (Exception e) {
logger.error("处理信息时发生异常", e);
}
} public NotifyMessageConverter getMessageConverter() {
return messageConverter;
} public void setMessageConverter(NotifyMessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
}
6.消息生产者Sender
package cn.carowl.activemq; import javax.servlet.ServletContext; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* 消息生产者
* @author weishengbin
*
*/
@Service
public class Sender {
private static ServletContext servletContext;
private static BeanFactory factory;
@Autowired
private QueueMessageProducer notifyMessageProducer; /**
* 发送点对点信息
*
* @param noticeInfo
*/
public void setQueueSender(String obj) {
// factory = new ClassPathXmlApplicationContext("classpath:/applicationContext-activemq.xml");
// factory.getBean("queueMessageProducer");
// QueueMessageProducer notifyMessageProducer = ((QueueMessageProducer) factory.getBean("queueMessageProducer"));
notifyMessageProducer.sendQueue(obj);
} public static ServletContext getServletContext() {
return servletContext;
} public static void setServletContext(ServletContext servletContext) {
Sender.servletContext = servletContext;
} public static BeanFactory getFactory() {
return factory;
} public static void setFactory(BeanFactory factory) {
Sender.factory = factory;
} }
7.发送消息TestSend
package cn.carowl.activemq; import javax.annotation.Resource; import org.springframework.http.MediaType;
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.ResponseBody; @Controller
@RequestMapping("/api")
public class TestSend {
@Resource(name="sender")
private Sender sender; @RequestMapping(value = "/send/test",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void send() {
sender.setQueueSender("发送的消息");
}
}
8.activemq配置文件applicationContext-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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <context:component-scan base-package="cn.carowl.activemq">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- ActiveMQ 连接工厂 -->
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
<bean id="connectinFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="failover:(tcp://localhost:61616)" />
<property name="closeTimeout" value="60000" />
<property name="userName" value="admin" />
<property name="password" value="admin" />
</bean>
<!-- Spring Caching连接工厂 -->
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="cachingConnectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
<property name="targetConnectionFactory" ref="connectinFactory"></property>
<!-- Session缓存数量 -->
<property name="sessionCacheSize" value="10"></property>
</bean> <!-- 配置消息发送目的地方式 -->
<!-- Queue队列:仅有一个订阅者会收到消息,消息一旦被处理就不会存在队列中 -->
<bean id="notifyQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="q.notify"></constructor-arg>
</bean>
<!-- 目的地:Topic主题 :放入一个消息,所有订阅者都会收到 -->
<!--这个是主题目的地,一对多的 -->
<bean id="notifyTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="t.notify"></constructor-arg>
</bean>
<!-- Spring JMS Template 配置JMS模版 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="cachingConnectionFactory" />
</bean>
<!-- 使用Spring JmsTemplate 的消息生产者 -->
<bean id="queueMessageProducer" class="cn.carowl.activemq.QueueMessageProducer">
<property name="jmsTemplate" ref="jmsTemplate"></property>
<property name="notifyQueue" ref="notifyQueue"></property>
<property name="messageConverter" ref="messageConverter"></property>
</bean>
<!-- <bean id="topicMessageProducer" class="cn.carowl.activemq.TopicMessageProducer">
<property name="jmsTemplate" ref="jmsTemplate"></property>
<property name="notifyTopic" ref="notifyTopic"></property>
<property name="messageConverter" ref="messageConverter"></property>
</bean> --> <!-- 消息消费者 一般使用spring的MDP异步接收Queue模式 -->
<!-- 消息监听容器 -->
<bean id="queueContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectinFactory"></property>
<property name="destination" ref="notifyQueue"></property>
<property name="messageListener" ref="queueMessageListener"></property>
</bean> <!-- 消息监听容器
<bean id="topicContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectinFactory"></property>
<property name="destination" ref="notifyTopic"></property>
<property name="messageListener" ref="topicMessageListener"></property>
<property name="pubSubDomain" value="true" />
</bean> --> <!-- 异步接收消息处理类 -->
<bean id="queueMessageListener" class="cn.carowl.activemq.QueueMessageListener">
<property name="messageConverter" ref="messageConverter"></property>
</bean>
<!-- <bean id="topicMessageListener" class="cn.carowl.activemq.TopicMessageListener">
<property name="messageConverter" ref="messageConverter"></property>
</bean> -->
<bean id="messageConverter" class="cn.carowl.activemq.NotifyMessageConverter">
</bean> </beans>
9.配置前端控制器web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext.xml,
classpath*:/applicationContext-shiro.xml,
classpath*:/applicationContext-activemq.xml
</param-value>
</context-param> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
10.启动服务,浏览器访问接口路径,测试发送消息是否成功!
-->
-->
-->
消息中间件activemq-5.13.0整合spring的更多相关文章
- 淘淘商城项目_同步索引库问题分析 + ActiveMQ介绍/安装/使用 + ActiveMQ整合spring + 使用ActiveMQ实现添加商品后同步索引库_匠心笔记
文章目录 1.同步索引库问题分析 2.ActiveM的介绍 2.1.什么是ActiveMQ 2.2.ActiveMQ的消息形式 3.ActiveMQ的安装 3.1.安装环境 3.2.安装步骤 4.Ac ...
- Java ActiveMQ 讲解(二)Spring ActiveMQ整合+注解消息监听
对于ActiveMQ消息的发送,原声的api操作繁琐,而且如果不进行二次封装,打开关闭会话以及各种创建操作也是够够的了.那么,Spring提供了一个很方便的去收发消息的框架,spring jms.整合 ...
- 第二篇:SpringBoot2.0整合ActiveMQ
本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...
- ActiveMQ整合spring、同步索引库
1. Activemq整合spring 1.1. 使用方法 第一步:引用相关的jar包. <dependency> <groupId>org.springframework ...
- ActiveMQ之整合spring
ActiveMQ可以轻松的与Spring进行整合,Spring提供了一系列的接口类,非常的好用! 比如异步消息数据.异步发送邮件.异步消息查询等 <dependency> <grou ...
- JAVAEE——宜立方商城09:Activemq整合spring的应用场景、添加商品同步索引库、商品详情页面动态展示与使用缓存
1. 学习计划 1.Activemq整合spring的应用场景 2.添加商品同步索引库 3.商品详情页面动态展示 4.展示详情页面使用缓存 2. Activemq整合spring 2.1. 使用方法 ...
- Spring Boot 2.0 整合携程Apollo配置中心
原文:https://www.jianshu.com/p/23d695af7e80 Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境.不同集群的配置,配置修改后能够 ...
- e3mall商城的归纳总结9之activemq整合spring、redis的缓存
敬给读者 本节主要给大家说一下activemq整合spring,该如何进行配置,上一节我们说了activemq的搭建和测试(单独测试),想看的可以点击时空隧道前去查看.讲完了之后我们还说一说在项目中使 ...
- spring boot 2.0 整合 elasticsearch6.5.3,spring boot 2.0 整合 elasticsearch NoNodeAvailableException
原文地址:spring boot 2.0 整合 elasticsearch NoNodeAvailableException 原文说的有点问题,下面贴出我的配置: 原码云项目地址:https://gi ...
随机推荐
- LeetCode: Minimum Depth of Binary Tree 解题报告
Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the n ...
- Natural Language Processing, 2017, Mar.29, Weekly Report
Distributed Representations of Words and Phrases and their Compositionality T Mikolov, I Sutskever, ...
- shell数组应用
引言 在Linux平台上工作,我们经常需要使用shell来编写一些有用.有意义的脚本程序.有时,会经常使用shell数组.那么,shell中的数组是怎么表现的呢,又是怎么定义的呢?接下来逐一的进行讲解 ...
- Delphi调用JAVA的WebService上传XML文件(XE10.2+WIN764)
相关资料:1.http://blog.csdn.net/luojianfeng/article/details/512198902.http://blog.csdn.net/avsuper/artic ...
- 5. EM算法-高斯混合模型GMM+Lasso
1. EM算法-数学基础 2. EM算法-原理详解 3. EM算法-高斯混合模型GMM 4. EM算法-GMM代码实现 5. EM算法-高斯混合模型+Lasso 1. 前言 前面几篇博文对EM算法和G ...
- <[完整版]中国式价值投资>读书笔记
注重本金安全 股票价格的高级与股票的贵贱没有任何关系 同股同权的应该买便宜的 买未来有可能变得更大的优秀公司股票,只有他们的股价才有可能有持续向上的原动力 如果绝大多数投资者对股票高市盈率不是拒绝而是 ...
- ContentType和@ResponseBody
ContentType 为 application/x-www-form-urlencoded (表单)时,入参前不需要加@ResponseBody: ContentType 为 applicatio ...
- JS监听页面----无鼠标键盘动作,自动跳页
function ScreenSaver(settings){ this.settings = settings; this.nTimeout = this.settings.timeout; doc ...
- 【linux】——linux僵死进程的产生与避免
一个进程在调用exit命令结束自己的生命的时候,其实它并没有真正的被销毁, 而是留下一个称为僵死进程(Zombie)的数据结构(系统调用exit,它的作用是使进程退出,但也仅仅限于将一个正常的进程变成 ...
- solr报错 ERROR SolrDispatchFilter null:ClientAbortException: java.net.SocketException: Broken pipe 原因是nginx截断了请求
[root@localhost nginx]# lltotal 36drwx------. 2 www root 4096 Aug 13 13:25 client_body_tempdrwxr-xr- ...