一般的实现方案

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

 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. nefu 446 今年暑假不AC(贪心)

    Description “今年暑假不AC?” “是的.” “那你干什么呢?” “看世界杯呀,笨蛋!” “@#$%^&*%...” 确实如此,世界杯来了,球迷的节日也来了,估计很多ACMer也会 ...

  2. Git 开发新的功能分支

    软件开发中,总有无穷无尽的新的功能要不断的添加进来.添加一个新功能时,你肯定不希望因为一些实验性质的代码把主分支搞乱了, 所以每添加一个新功能,最好新建一个feature分支,在上面开发,完成后,合并 ...

  3. while;do while;switch;break;continue

    1.while: 格式:while(判断条件) {    满足条件要执行的语句    } while语句与for语句对比(小九九) 1.1  for <script>for (var i= ...

  4. TransactionScope的使用

    本文导读:在实际开发工作中,执行一个事件,然后调用另一接口插入数据,如果处理逻辑出现异常,那么之前插入的数据将成为垃圾数据,我们所希望的是能够在整个这个方法定义为一个事务,TransactionSco ...

  5. 使用onclick跳转到其他页面。使用button跳转到指定url

    1. onclick="javascript:window.location.href='aa.htm'" 2.  onclick="location='URL'&quo ...

  6. 在vim中使用perltidy美化perl代码

    来源: http://www.cnblogs.com/itech/archive/2013/02/18/2915279.html 格式优美的perl代码不但让人赏心悦目,而且可以方便阅读. perlt ...

  7. http get with body data

    http://stackoverflow.com/questions/978061/http-get-with-request-body Yes, you can send a request bod ...

  8. HTTPclient cookie的获取与设置

    因为代码与Java用apache的HttpClient发送Post请求大部份重复,所以就不贴整段代码了,只把不同的地方贴出来.发送Cookie就必须先得到Cookie,所以至少发送两次请求,第一次用于 ...

  9. ORA-12170: TNS:Connect timeout occurred

    VM 作为ORACLE 服务器,客户端登陆提示超时,本地连接使用网络连接正常. D:>sqlplus system/oracle123@//192.168.63.121:15021/pdb01 ...

  10. sed awk 小例

    实现数据库批量更新与回滚 create database awktest; use awktest create table user(    id int unsigned not null uni ...