一般的实现方案

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

 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. Codeforces Round #350 (Div. 2)_D2 - Magic Powder - 2

    D2. Magic Powder - 2 time limit per test 1 second memory limit per test 256 megabytes input standard ...

  2. A*搜寻算法(A星算法)

    A*搜寻算法[编辑] 维基百科,自由的百科全书 本条目需要补充更多来源.(2015年6月30日) 请协助添加多方面可靠来源以改善这篇条目,无法查证的内容可能会被提出异议而移除. A*搜索算法,俗称A星 ...

  3. Inno Setup入门(六)——在程序目录下创建文件

    创建文件夹可以使用[dirs]段实现,代码如下: [setup] ;全局设置,本段必须 AppName=Test AppVerName=TEST DefaultDirName="E:\TES ...

  4. git 查看当前与上一次version的差异

    http://stackoverflow.com/questions/9903541/finding-diff-between-current-and-last-versions up vote47d ...

  5. 【转】linux ls -l的详解

    原文:http://blog.csdn.net/sjzs5590/article/details/8254527 以root的家目录为例: 可以看到,用ls -l命令查看某一个目录会得到一个7个字段的 ...

  6. 转 linux下xargs命令用法详解

    xargs在linux中是个很有用的命令,它经常和其他命令组合起来使用,非常的灵活. xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具.它把一个数据流分割为一些足够小的块,以方便过滤 ...

  7. 页面开发辅助类—HtmlHelper初步了解

    1.1 有失必有得 在ASP.Net MVC中微软并没有提供类似服务器端控件那种开发方式,毕竟微软的MVC就是传统的请求处理响应的回归.所以抛弃之前的那种事件响应的模型,抛弃服务器端控件也理所当然. ...

  8. NSUserDefault -- synchronize 浅析

    NSUserDefault的使用比较简单:NSUserDefaults *mySettingData = [NSUserDefaults standardUserDefaults];  创建NSUse ...

  9. Android中购物车的全选、反选、问题和计算价格

    此Demo主要解决的是购物车中的全选,反选计算价格和选中的条目个数的问题,当选中几条时,点击反选,会把当先选中的变为不选中,把不选中的变为选中.点击全选会全部选中,再次点击时,变为全部不选中. //- ...

  10. gulp相关知识(2)

    将之前的东西的理论部分整理了一下—— gulp 前端构建工具 它可以帮助我们完成一些自动化操作 它需要一些插件的支持 var gulp = require('gulp'); --> gulp命令 ...