一般的实现方案

发送异步消息所使用的工具类:

 import java.util.Date;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
@Component
public class AsyncUtils {
private static Logger log = LoggerFactory.getLogger(AsyncUtils.class);
private static JmsTemplate jmsTemplate;
private static Destination sendMailDestination;
private static Destination LoginLogDestination;
private static Destination normalLogDestination;
private static Destination pushNotificationDestination;
public static void log(String type,String operate){
if(!SystemConfigFromDB.getBoolean(SystemConfigFromDB.NEED_NORMAL_LOG)){
return;
}
try{
User user = (User) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
if(user==null){
return;
}
OperateLog log = new OperateLog(user.getId(), user.getName(), operate,type, user.getLastLoginIp());
final ActiveMQObjectMessage message = new ActiveMQObjectMessage();
message.setObject(log);
//AsycWorkFactory.sendMessage(message, AsycWork.NORMAL_LOG);
jmsTemplate.send(normalLogDestination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return message;
}
});
}catch (Exception e) {
log.error("日志记录出错!", e);
}
}
public static void sendMail(String address,String title,String content){
if(!SystemConfigFromDB.getBoolean(SystemConfigFromDB.NEED_SEND_MAIL)){
return;
}
try{
final ActiveMQMapMessage message = new ActiveMQMapMessage();
message.setString("address", address);
message.setString("title", title);
message.setString("content", content);
//AsycWorkFactory.sendMessage(message, AsycWork.EMAIL);
jmsTemplate.send(sendMailDestination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return message;
}
});
}catch (Exception e) {
log.error("邮件发送出错!",e);
}
}
public static void loginLog(String uid,String ip,Date date){
if(!SystemConfigFromDB.getBoolean(SystemConfigFromDB.NEED_LOG_CLIENTUSER_LOGINLOG)){
return;
}
try{
final ActiveMQMapMessage message = new ActiveMQMapMessage();
message.setString("uid", uid);
message.setString("ip", ip);
message.setString("date", DateUtils.formatDateTime(date, "yyyy-MM-dd HH:mm:ss"));
//AsycWorkFactory.sendMessage(message, AsycWork.LOGIN_LOG);
jmsTemplate.send(LoginLogDestination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return message;
}
});
}catch (Exception e) {
log.error("邮件发送出错!",e);
}
}
public static void pushNotification(String id,String content){
if(!SystemConfigFromDB.getBoolean(SystemConfigFromDB.NEED_LOG_CLIENTUSER_LOGINLOG)){
return;
}
try{
final ActiveMQMapMessage message = new ActiveMQMapMessage();
message.setString("id", id);
message.setString("content", content);
jmsTemplate.send(normalLogDestination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return message;
}
});
}catch (Exception e) {
log.error("消息推送出错!",e);
}
}
@Autowired
public void setJmsTemplate(JmsTemplate jmsTemplate) {
AsyncUtils.jmsTemplate = jmsTemplate;
}
@Autowired
@Qualifier("sendMailDestination")
public void setSendMailDestination(Destination sendMailDestination) {
AsyncUtils.sendMailDestination = sendMailDestination;
}
@Autowired
@Qualifier("LoginLogDestination")
public void setLoginLogDestination(Destination loginLogDestination) {
LoginLogDestination = loginLogDestination;
}
@Autowired
@Qualifier("normalLogDestination")
public void setNormalLogDestination(Destination normalLogDestination) {
AsyncUtils.normalLogDestination = normalLogDestination;
}
@Autowired
@Qualifier("pushNotificationDestination")
public void setPushNotificationDestination(
Destination pushNotificationDestination) {
AsyncUtils.pushNotificationDestination = pushNotificationDestination;
}
}

监听异步消息的监听器类(可以给每个类型的消息设定不同的监听器):

 @Component
public class EmailListener implements MessageListener {
private static Logger log = LoggerFactory.getLogger(EmailListener.class);
@Override
public void onMessage(Message message) {
ActiveMQMapMessage msg = (ActiveMQMapMessage) message;
try {
String address = msg.getString("address");
String title = msg.getString("title");
String content = msg.getString("content");
Constants.sendMail(address, title, content);
} catch (Exception e) {
log.error("异步邮件发送异常", e);
}
}
}

使用方式:

//异步发送邮件
AsyncUtils.sendMail("邮件地址","主题","内容");
//即可

Spring配置文件:

 <?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:aop="http://www.springframework.org/schema/aop"
xmlns:core="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.9.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<!-- ActiveMQ 异步任务 -->
<context:annotation-config/>
<!-- 存放异步操作相关需要Spring管理的类的包 -->
<context:component-scan base-package="com.xxx.core.async" />
<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://192.168.7.21:61616" />
</bean>
<!-- 带连接池的JMS链接工厂 -->
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
<property name="connectionFactory" ref="targetConnectionFactory" />
<property name="maxConnections" value="10" />
</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" />
</bean>
<bean id="sendMailDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="SendEmail"/>
</bean>
<bean id="LoginLogDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="LoginLog"/>
</bean>
<bean id="normalLogDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="NormalLog"/>
</bean>
<bean id="pushNotificationDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="Notification"/>
</bean>
<!-- 消息监听容器 -->
<bean id="jmsEmailContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="sendMailDestination" />
<property name="messageListener" ref="emailListener" /> <!-- 设置监听对象 -->
</bean>
<bean id="jmsLoginLogContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="LoginLogDestination" />
<property name="messageListener" ref="loginLogListener" /> <!-- 设置监听对象 -->
</bean>
<bean id="jmsNormalLogContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="normalLogDestination" />
<property name="messageListener" ref="normalLogListener" /> <!-- 设置监听对象 -->
</bean>
<bean id="jmsNotificationContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="pushNotificationDestination" />
<property name="messageListener" ref="pushNotificationListener" /> <!-- 设置监听对象 -->
</bean>
</beans>

基于Spring的异步系统实现方案的更多相关文章

  1. 如何有效地配置基于Spring的应用系统

    Spring为应用系统的开发提供了极大的方便,其IoC反向注入(或DI依赖注入)的概念也彻底地改变了旧的编程方式,让我们只需关注如何使用对象,而创建对象交给Spring去完成,即把使用对象和创建对象分 ...

  2. 基于Spring框架应用的权限控制系统的研究和实现

    摘 要: Spring框架是一个优秀的多层J2EE系统框架,Spring本身没有提供对系统的安全性支持.Acegi是基于Spring IOC 和 AOP机制实现的一个安全框架.本文探讨了Acegi安全 ...

  3. 基于Spring实现策略模式

    背景: 看多很多策略模式,总结下来实现原理大体都差不多,在这里主要是讲解下自己基于Spring更优雅的实现方案:这个方案主要是看了一些开源rpc和Spring相关源码后的一些思路,所以在此进行总结 首 ...

  4. 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践

    由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...

  5. spring security 一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中 配置的Bean,充分利用了Spring ...

  6. Weshop基于Spring Cloud开发的小程序商城系统

    WESHOP | 基于微服务的小程序商城系统 Weshop是基于Spring Cloud(Greenwich)开发的小程序商城系统,提供整套公共微服务服务模块,包含用户中心.商品中心.订单中心.营销中 ...

  7. 基于Spring Boot的在线问卷调查系统的设计与实现+论文

    全部源码下载 # 基于Spring Boot的问卷调查系统 ## 介绍 > * 本项目的在线问卷调查调查系统是基于Spring Boot 开发的,采用了前后端分离模式来开发. > * 前端 ...

  8. 基于Web在线考试系统的设计与实现

    这是一个课程设计的文档,源码及文档数据库我都修改过了,貌似这里复制过来的时候图片不能贴出,下载地址:http://download.csdn.net/detail/sdksdk0/9361973   ...

  9. 干货|基于 Spring Cloud 的微服务落地

    转自 微服务架构模式的核心在于如何识别服务的边界,设计出合理的微服务.但如果要将微服务架构运用到生产项目上,并且能够发挥该架构模式的重要作用,则需要微服务框架的支持. 在Java生态圈,目前使用较多的 ...

随机推荐

  1. HDU 4857 逃生(反向拓扑排序+优先队列)

    ( ̄▽ ̄)" //这题对序号输出有要求,较小的序号优先输出,所以用到优先队列 //优先队列是优先弹出值最大的,所以最后要反向输出结果,才是正确的output #include<iost ...

  2. 关于Spring Security 3获取用户信息的问题

    标签: spring security 3标签获取用户信息 2013-01-05 10:40 5342人阅读 评论(0) 收藏 举报  分类: Spring(25) java(70) 前端(7)    ...

  3. [转载] 关于Windows Boot Manager、Bootmgfw.efi、Bootx64.efi、bcdboot.exe 的详解

    原帖: http://bbs.wuyou.net/forum.php?mod=viewthread&tid=303679 前言:1.本教程针对于UEFI启动来叙述的,根据普遍的支持UEFI的机 ...

  4. Qt Quick 简单教程

    上一篇<Qt Quick 之 Hello World 图文详解>我们已经分别在电脑和 Android 手机上运行了第一个 Qt Quick 示例—— HelloQtQuickApp ,这篇 ...

  5. Qt之Windows开发移植问题汇总

    来源:http://blog.sina.com.cn/s/blog_a6fb6cc90101auw6.html 在用Qt开发完成项目后,就需要将其打包并且移植在其他机器上,能在其他PC机上正常跑起来才 ...

  6. byte数组转16进制 输出到文件

    try { File file = new File(Environment.getExternalStorageDirectory(),"shuju2"); if(!file.e ...

  7. php redis 消息队列

    redis是什么东西就不多说了,网上文章一搜一大堆. 首先来说一下我要实现的功能: 类似一个消息中转站吧,如果有人要发送消息,先将消息发到我这里来,然后我这边进行转发,为的就是有一个统一的管理和修改时 ...

  8. Checking the Calendar

    Checking the Calendar time limit per test 1 second memory limit per test 256 megabytes input standar ...

  9. js遍历table 和 jquery 遍历table

    <span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255) ...

  10. 学习笔记——组合模式Composite

    组合模式,典型的层次结构. 与装饰器类图相似. 区别在于:装饰器模式是为了在接口中增加方法,而组合模式在于层次元素的叠加. ConcreteComponent就是中间结点,可以包含更多的Concret ...