ActiveMQ可以轻松的与Spring进行整合,Spring提供了一系列的接口类,非常的好用!

比如异步消息数据、异步发送邮件、异步消息查询等

<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.11.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>

  

先引入两个activeMQ的jar包,

然后进行spring-activemq进行配制:

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="false"> <!-- 第三方MQ工厂: ConnectionFactory -->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- ActiveMQ Address -->
<property name="brokerURL" value="${activemq.brokerURL}" />
<property name="userName" value="${activemq.userName}"></property>
<property name="password" value="${activemq.password}"></property>
</bean> <!--
ActiveMQ为我们提供了一个PooledConnectionFactory,通过往里面注入一个ActiveMQConnectionFactory
可以用来将Connection、Session和MessageProducer池化,这样可以大大的减少我们的资源消耗,要依赖于 activemq-pool包
-->
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
<property name="connectionFactory" ref="targetConnectionFactory" />
<property name="maxConnections" value="${activemq.pool.maxConnections}" />
</bean> <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
<property name="targetConnectionFactory" ref="pooledConnectionFactory" />
</bean> <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
<!-- 队列模板 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestinationName" value="${activemq.queueName}"></property>
</bean> </beans>

创建好第三方MQ工厂: ConnectionFactory

然后创建生产者MQProducer :

package bhz.mq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service; import bhz.entity.Mail; import com.alibaba.fastjson.JSONObject; /**
* <B>系统名称:</B><BR>
* <B>模块名称:</B><BR>
* <B>中文类名:</B><BR>
* <B>概要说明:</B><BR>
* @author jxh
*/
@Service("mqProducer")
public class MQProducer { private JmsTemplate jmsTemplate; public JmsTemplate getJmsTemplate() {
return jmsTemplate;
} @Autowired
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
} /**
* <B>方法名称:</B>发送邮件信息对象<BR>
* <B>概要说明:</B>发送邮件信息对象<BR>
* @param mail
*/
public void sendMessage(final Mail mail) {
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(JSONObject.toJSONString(mail));
}
});
} }

看一下mail实体类:

package bhz.entity;

public class Mail {

	/** 发件人 **/
private String from;
/** 收件人 **/
private String to;
/** 主题 **/
private String subject;
/** 邮件内容 **/
private String content; public Mail(){} public Mail(String from, String to, String subject, String content) {
super();
this.from = from;
this.to = to;
this.subject = subject;
this.content = content;
} public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
} }

 下面进行消息的发送,通过junit进行发送测试:

package bhz.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import bhz.entity.Mail;
import bhz.mq.MQProducer; /**
* <B>系统名称:</B><BR>
* <B>模块名称:</B><BR>
* <B>中文类名:</B><BR>
* <B>概要说明:</B><BR>
* @author jxh
*/
@ContextConfiguration(locations = {"classpath:spring-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestProducer { @Autowired
private MQProducer mqProducer; @Test
public void send(){
Mail mail = new Mail();
mail.setTo("174754613@qq.com");
mail.setSubject("异步发送邮件");
mail.setContent("Hi,This is a message!"); this.mqProducer.sendMessage(mail);
System.out.println("发送成功.."); } }

下面看一下消费者的这个项目的配置activemq-consumer:

这个项目多一个config

## ActiveMQ Configuration
activemq.brokerURL=tcp\://192.168.1.200\:61616
activemq.userName=bhz
activemq.password=bhz
activemq.pool.maxConnections=10
#queueName
activemq.queueName=mailqueue ## SMTP Configuration
mail.host=smtp.163.com
##mail.port=21
mail.username=***@163.com
mail.password=
mail.smtp.auth=true
mail.smtp.timeout=30000
mail.default.from=***@163.com

看一下消费者的consumer的spring-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="false"> <!-- 第三方MQ工厂: ConnectionFactory -->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<!-- ActiveMQ服务地址 -->
<property name="brokerURL" value="${activemq.brokerURL}" />
<property name="userName" value="${activemq.userName}"></property>
<property name="password" value="${activemq.password}"></property>
</bean> <!--
ActiveMQ为我们提供了一个PooledConnectionFactory,通过往里面注入一个ActiveMQConnectionFactory
可以用来将Connection、Session和MessageProducer池化,这样可以大大的减少我们的资源消耗,要依赖于 activemq-pool包
-->
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
<property name="connectionFactory" ref="targetConnectionFactory" />
<property name="maxConnections" value="${activemq.pool.maxConnections}" />
</bean> <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
<property name="targetConnectionFactory" ref="pooledConnectionFactory" />
</bean> <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 --> <!-- 队列模板 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestinationName" value="${activemq.queueName}"></property>
</bean> <!--这个是目的地:mailQueue -->
<bean id="mailQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg>
<value>${activemq.queueName}</value>
</constructor-arg>
</bean> <!-- 配置自定义监听:MessageListener -->
<bean id="mailQueueMessageListener" class="bhz.mq.MailQueueMessageListener"></bean> <!-- 将连接工厂、目标对了、自定义监听注入jms模板 -->
<bean id="sessionAwareListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="mailQueue" />
<property name="messageListener" ref="mailQueueMessageListener" />
</bean>
</beans>

因为要发送邮件,这边还有一个邮件的配置:

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"> <!-- Spring提供的发送电子邮件的高级抽象类 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="defaultEncoding" value="UTF-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
</props>
</property>
</bean> <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from">
<value>${mail.default.from}</value>
</property>
</bean> <!-- 配置线程池 -->
<bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 线程池维护线程的最少数量 -->
<property name="corePoolSize" value="5" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="30000" />
<!-- 线程池维护线程的最大数量 -->
<property name="maxPoolSize" value="50" />
<!-- 线程池所使用的缓冲队列 -->
<property name="queueCapacity" value="100" />
</bean> </beans>

 mail实体类和前面一样,

看一下接收消息的Listener,

package bhz.mq;

import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component; import bhz.entity.Mail;
import bhz.service.MailService; import com.alibaba.fastjson.JSONObject; /**
* <B>系统名称:</B><BR>
* <B>模块名称:</B><BR>
* <B>中文类名:</B><BR>
* <B>概要说明:</B><BR>
* @author jxh
*/
@Component
public class MailQueueMessageListener implements SessionAwareMessageListener<Message> { @Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Destination mailQueue;
@Autowired
private MailService mailService; public synchronized void onMessage(Message message, Session session) {
try {
TextMessage msg = (TextMessage) message;
final String ms = msg.getText();
System.out.println("收到消息:" + ms);
//转换成相应的对象
Mail mail = JSONObject.parseObject(ms, Mail.class);
if (mail == null) {
return;
}
try {
//执行发送业务
mailService.mailSend(mail); } catch (Exception e) {
// 发送异常,重新放回队列
// jmsTemplate.send(mailQueue, new MessageCreator() {
// @Override
// public Message createMessage(Session session) throws JMSException {
// return session.createTextMessage(ms);
// }
// });
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

最后调用发送邮件的service,进行邮件发送:

package bhz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service; import bhz.entity.Mail; @Service("mailService")
public class MailService { @Autowired
private JavaMailSender mailSender;
@Autowired
private SimpleMailMessage simpleMailMessage;
@Autowired
private ThreadPoolTaskExecutor threadPool; /**
* <B>方法名称:</B>发送邮件<BR>
* <B>概要说明:</B>发送邮件<BR>
* @param mail
*/
public void mailSend(final Mail mail) {
threadPool.execute(new Runnable() {
public void run() {
try {
simpleMailMessage.setFrom(simpleMailMessage.getFrom());
simpleMailMessage.setTo(mail.getTo());
simpleMailMessage.setSubject(mail.getSubject());
simpleMailMessage.setText(mail.getContent());
mailSender.send(simpleMailMessage);
} catch (MailException e) {
e.printStackTrace();
throw e;
}
}
});
}
}

  邮件配置是指完成后,就可以正常发送邮件了,这就是通过activemq异步发送邮件。

  

 

ActiveMQ之整合spring的更多相关文章

  1. activeMq 消费者整合spring

    package com.mq.consumer; import javax.jms.JMSException;import javax.jms.Message;import javax.jms.Mes ...

  2. 消息中间件-activemq实战整合Spring之Topic模式(五)

    这一节我们看一下Topic模式下的消息发布是如何处理的. applicationContext-ActiveMQ.xml配置: <?xml version="1.0" enc ...

  3. ActiveMQ整合spring、同步索引库

    1.   Activemq整合spring 1.1. 使用方法 第一步:引用相关的jar包. <dependency> <groupId>org.springframework ...

  4. JAVAEE——宜立方商城09:Activemq整合spring的应用场景、添加商品同步索引库、商品详情页面动态展示与使用缓存

    1. 学习计划 1.Activemq整合spring的应用场景 2.添加商品同步索引库 3.商品详情页面动态展示 4.展示详情页面使用缓存 2. Activemq整合spring 2.1. 使用方法 ...

  5. 淘淘商城项目_同步索引库问题分析 + ActiveMQ介绍/安装/使用 + ActiveMQ整合spring + 使用ActiveMQ实现添加商品后同步索引库_匠心笔记

    文章目录 1.同步索引库问题分析 2.ActiveM的介绍 2.1.什么是ActiveMQ 2.2.ActiveMQ的消息形式 3.ActiveMQ的安装 3.1.安装环境 3.2.安装步骤 4.Ac ...

  6. ActiveMQ学习总结------Spring整合ActiveMQ 04

    通过前几篇的学习,相信大家已经对我们的ActiveMQ的原生操作已经有了个深刻的概念, 那么这篇文章就来带领大家一步一步学习下ActiveMQ结合Spring的实战操作 注:本文将省略一部分与Acti ...

  7. e3mall商城的归纳总结9之activemq整合spring、redis的缓存

    敬给读者 本节主要给大家说一下activemq整合spring,该如何进行配置,上一节我们说了activemq的搭建和测试(单独测试),想看的可以点击时空隧道前去查看.讲完了之后我们还说一说在项目中使 ...

  8. JMS(java消息服务)整合Spring项目案例

    转载自云栖社区 摘要: Sprng-jms消息服务小项目 所需的包: spring的基础包 spring-jms-xx包 spring-message–xx包 commons-collection-x ...

  9. Web项目容器集成ActiveMQ & SpringBoot整合ActiveMQ

    集成tomcat就是随项目启动而启动tomcat,最简单的方法就是监听器监听容器创建之后以Broker的方式启动ActiveMQ. 1.web项目中Broker启动的方式进行集成 在这里采用Liste ...

随机推荐

  1. 机器学习进阶-图像梯度计算-scharr算子与laplacian算子(拉普拉斯) 1.cv2.Scharr(使用scharr算子进行计算) 2.cv2.laplician(使用拉普拉斯算子进行计算)

    1. cv2.Scharr(src,ddepth, dx, dy), 使用Scharr算子进行计算 参数说明:src表示输入的图片,ddepth表示图片的深度,通常使用-1, 这里使用cv2.CV_6 ...

  2. WPF中TextBox文件拖放问题

    在WPF中,当我们尝试向TextBox中拖放文件,从而获取其路径时,往往无法成功(拖放文字可以成功).造成这种原因关键是WPF的TextBox对拖放事件处理机制的不同,具体可参考这篇文章Textbox ...

  3. 02-body标签中相关标签-1

    主要内容: 字体标签: h1~h6.<font>.<u>.<b>.<strong><em>.<sup>.<sub> ...

  4. C++11之for循环的新用法《转》

    相关资料:https://legacy.gitbook.com/book/changkun/cpp1x-tutorial/details C++11之for循环的新用法 C++使用如下方法遍历一个容器 ...

  5. Python : 什么是*args和**kwargs

    让生活Web个够 先来看个例子: def foo(*args, **kwargs): print 'args = ', args print 'kwargs = ', kwargs print '-- ...

  6. js Json数组的增删改查

    <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> ...

  7. Shell编程:小白初步

    shell类型: shell的历史网络上有一大堆,这里就不介绍了.但是我们的Linux系统上是有许多种shell的我们可以查看:使用命令 vi /etc/passwd 可以查看用户对应的shell(其 ...

  8. jsp开发环境搭建(windows64位)

    有些东西当时学和用的时候很熟练,但如果时间久了不用了,再次遇到的时候,也会很生疏,现在对一般的jsp网站开发环境的搭建做一个小结,以备以后不时之需,作为参考手册用. 一.java环境搭建 1.下载jd ...

  9. sql中优化查询

    1.在大部分情况下,where条件语句中包含or.not,SQL将不使用索引:可以用in代替or,用比较运算符!=代替not. 2.在没有必要显示不重复运行时,不使用distinct关键字,避免增加处 ...

  10. js 改变颜色值

    /** * 获取颜色值 */ const color2RGB = (color) => { if (typeof color !== 'string' || (color.length !== ...