一般的实现方案

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

 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 2544 最短路(dijkstra+邻接矩阵)

    ( ̄▽ ̄)" #include<iostream> #include<cstdio> using namespace std; const int INF=10e7; ...

  2. ocs添加仓库受限问题

    添加仓库时受限出现以下问题 如图: 解决方法 修改app\ome\lib\branch\func.php文件的allow_use_num方法 /** * 允许使用的仓库数 * @access publ ...

  3. MJExtension的使用

    1. Plist → 模型数组 控制器中引用#import "MJExtension.h" 模型数组 = [模型类名 objectArrayWithFilename:@" ...

  4. 有了SSL证书,如何在IIS环境下部署https?【转载】

    昨天各位小伙伴都很开心的领取了自己的SSL证书,但是大部分小伙伴却不知道如何部署,也许是因为第一次接触SSL这种高端的东西吧,不过个人觉得就是懒懒懒...本来小编也挺懒的,但是答应了各位小伙伴的,那么 ...

  5. QQ登录界面

    @property (nonatomic,assign) IBOutlet UITextField *qq; @property (nonatomic,assign) IBOutlet UITextF ...

  6. 查看端口号他所占用的exe应用程序

  7. UML示例图

  8. MYSQL和ORACLE的触发器与存储过程语法差异

    整改了一番脚本,遇到了一些两种数据库之间的差异,记录一下: 触发器: 差异 MYSQL ORACLE 说明 创建语句不同 create trigger `AA` BEFORE INSERT on `B ...

  9. UVA 10308 Roads in the North

    input u1 v1 w1 u2 v2 w2 ... un vn wn 1<=vi,ui<=n+1 /n output 距离最远的两个点的距离 做法:一颗全连通且只有一条路从一个顶点到达 ...

  10. IO包中的其他类

    查看各对象API文档 打印流 PrintWriter PrintStream 序列流:对多个流进行排列合并 SequenceInputStream public static void main(St ...