JMS-Spring事务管理

第一部分 - 注解实现

配置JmsTransactionManager

  • 创建一个JmsTransactionManager作为PlatformTransactionManager的实现;
  • 将这个JmsTransactionManager配置到JmsTemplate和JmsListener中,程序中的所有JmsListener都将受这个JmsTransactionManager的控制;
package com.example.demo.config;

import com.example.demo.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.connection.JmsTransactionManager;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.PlatformTransactionManager;

import javax.jms.ConnectionFactory;

@EnableJms
@Configuration
public class JmsConfig {

    private static final Logger LOG = LoggerFactory.getLogger(CustomerService.class);

    @Bean
    public PlatformTransactionManager transactionManager(ConnectionFactory connectionFactory) {
        return new JmsTransactionManager(connectionFactory);
    }

    @Bean
    public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
        LOG.debug("init jms template with converter.");
        JmsTemplate template = new JmsTemplate();
        template.setConnectionFactory(connectionFactory);
        return template;
    }

    @Bean
    public JmsListenerContainerFactory<?> msgFactory(ConnectionFactory connectionFactory,
                                                     DefaultJmsListenerContainerFactoryConfigurer configurer,
                                                     PlatformTransactionManager transactionManager) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setTransactionManager(transactionManager);
        factory.setReceiveTimeout(10000L);
        configurer.configure(factory, connectionFactory);
        return factory;
    }

}

使用配置的JmsTransactionManager

  • @Transactional
  • @JmsListener(destination = "customer:msg1:new", containerFactory = "msgFactory")
package com.example.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CustomerService {

    private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);

    @Autowired
    private JmsTemplate jmsTemplate;

    @Transactional
    @JmsListener(destination = "customer:msg1:new", containerFactory = "msgFactory")
    public void handle(String msg) {
        logger.info("Get msg1 : {}", msg);
        String reply = "Reply - " + msg;
        jmsTemplate.convertAndSend("customer:msg:reply", reply);
        if (msg.contains("error")) {
            simulateError();
        }
    }

    private void simulateError() {
        throw new RuntimeException("some Data error.");
    }

}

启动程序

  • 每隔10s创建一个事务;
2018-06-28 18:08:37.938 DEBUG 2344 --- [enerContainer-1] o.s.j.connection.JmsTransactionManager   : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-06-28 18:08:37.942  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : Using Persistence Adapter: MemoryPersistenceAdapter
2018-06-28 18:08:37.943  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.14.5 (localhost, ID:LiXinlei-RSC-62286-1530180507423-0:2) is starting
2018-06-28 18:08:37.944  INFO 2344 --- [  JMX connector] o.a.a.broker.jmx.ManagementContext       : JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
2018-06-28 18:08:37.945  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.14.5 (localhost, ID:LiXinlei-RSC-62286-1530180507423-0:2) started
2018-06-28 18:08:37.945  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : For help or more information please see: http://activemq.apache.org
2018-06-28 18:08:37.951  INFO 2344 --- [enerContainer-1] o.a.activemq.broker.TransportConnector   : Connector vm://localhost started
2018-06-28 18:08:37.956 DEBUG 2344 --- [enerContainer-1] o.s.j.connection.JmsTransactionManager   : Created JMS transaction on Session [ActiveMQSession {id=ID:LiXinlei-RSC-62286-1530180507423-4:2:1,started=false} java.lang.Object@65f14f13] from Connection [ActiveMQConnection {id=ID:LiXinlei-RSC-62286-1530180507423-4:2,clientId=ID:LiXinlei-RSC-62286-1530180507423-3:2,started=false}]
2018-06-28 18:08:47.963 DEBUG 2344 --- [enerContainer-1] o.s.j.connection.JmsTransactionManager   : Initiating transaction commit
2018-06-28 18:08:47.964 DEBUG 2344 --- [enerContainer-1] o.s.j.connection.JmsTransactionManager   : Committing JMS transaction on Session [ActiveMQSession {id=ID:LiXinlei-RSC-62286-1530180507423-4:2:1,started=true} java.lang.Object@65f14f13]
2018-06-28 18:08:47.967  INFO 2344 --- [enerContainer-1] o.a.activemq.broker.TransportConnector   : Connector vm://localhost stopped
2018-06-28 18:08:47.970  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.14.5 (localhost, ID:LiXinlei-RSC-62286-1530180507423-0:2) is shutting down
2018-06-28 18:08:47.973  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.14.5 (localhost, ID:LiXinlei-RSC-62286-1530180507423-0:2) uptime 10.034 seconds
2018-06-28 18:08:47.974  INFO 2344 --- [enerContainer-1] o.apache.activemq.broker.BrokerService   : Apache ActiveMQ 5.14.5 (localhost, ID:LiXinlei-RSC-62286-1530180507423-0:2) is shutdown

实验1 - 直接调用service层的handle

2018-06-28 18:32:11.364 DEBUG 18140 --- [nio-6666-exec-1] o.s.j.connection.JmsTransactionManager   : Creating new transaction with name [com.example.demo.service.CustomerService.handle]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2018-06-28 18:32:11.371 DEBUG 18140 --- [nio-6666-exec-1] o.s.j.connection.JmsTransactionManager   : Created JMS transaction on Session [ActiveMQSession {id=ID:LiXinlei-RSC-62565-1530181919410-4:3:1,started=false} java.lang.Object@72347a29] from Connection [ActiveMQConnection {id=ID:LiXinlei-RSC-62565-1530181919410-4:3,clientId=ID:LiXinlei-RSC-62565-1530181919410-3:3,started=false}]
2018-06-28 18:32:11.376  INFO 18140 --- [nio-6666-exec-1] c.example.demo.service.CustomerService   : Get msg1 : apple_error
2018-06-28 18:32:11.377 DEBUG 18140 --- [nio-6666-exec-1] o.springframework.jms.core.JmsTemplate   : Executing callback on JMS Session: ActiveMQSession {id=ID:LiXinlei-RSC-62565-1530181919410-4:3:1,started=false} java.lang.Object@72347a29
2018-06-28 18:32:11.390 DEBUG 18140 --- [nio-6666-exec-1] o.springframework.jms.core.JmsTemplate   : Sending created message: ActiveMQTextMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = false, droppable = false, jmsXGroupFirstForConsumer = false, text = Reply - apple_error}
2018-06-28 18:32:11.392 DEBUG 18140 --- [nio-6666-exec-1] o.s.j.connection.JmsTransactionManager   : Initiating transaction rollback
2018-06-28 18:32:11.392 DEBUG 18140 --- [nio-6666-exec-1] o.s.j.connection.JmsTransactionManager   : Rolling back JMS transaction on Session [ActiveMQSession {id=ID:LiXinlei-RSC-62565-1530181919410-4:3:1,started=false} java.lang.Object@72347a29]
2018-06-28 18:32:11.405 ERROR 18140 --- [nio-6666-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: some Data error.] with root cause
null

实验1结论:

  • 由于受JmsTransactionManager的控制,直接从controller调service的handle方法也将收到事务的控制;

实验2 - service的handle方法因监听到MQ中的消息而被调用

2018-06-28 18:41:10.174 DEBUG 18140 --- [nio-6666-exec-9] o.springframework.jms.core.JmsTemplate   : Executing callback on JMS Session: ActiveMQSession {id=ID:LiXinlei-RSC-62565-1530181919410-4:61:1,started=false} java.lang.Object@41fbd9bc
2018-06-28 18:41:10.177 DEBUG 18140 --- [nio-6666-exec-9] o.springframework.jms.core.JmsTemplate   : Sending created message: ActiveMQTextMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = false, droppable = false, jmsXGroupFirstForConsumer = false, text = pineapple_error}
2018-06-28 18:41:10.182 DEBUG 18140 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer  : Received message of type [class org.apache.activemq.command.ActiveMQTextMessage] from consumer [ActiveMQMessageConsumer { value=ID:LiXinlei-RSC-62565-1530181919410-4:60:1:1, started=true }] of transactional session [ActiveMQSession {id=ID:LiXinlei-RSC-62565-1530181919410-4:60:1,started=true} java.lang.Object@3aaa5070]
2018-06-28 18:41:10.182 DEBUG 18140 --- [enerContainer-1] .s.j.l.a.MessagingMessageListenerAdapter : Processing [org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener$MessagingMessageConverterAdapter$LazyResolutionMessage@39af77e1]
2018-06-28 18:41:10.182 DEBUG 18140 --- [enerContainer-1] o.s.j.connection.JmsTransactionManager   : Participating in existing transaction
2018-06-28 18:41:10.182  INFO 18140 --- [enerContainer-1] c.example.demo.service.CustomerService   : Get msg1 : pineapple_error
2018-06-28 18:41:10.182 DEBUG 18140 --- [enerContainer-1] o.springframework.jms.core.JmsTemplate   : Executing callback on JMS Session: ActiveMQSession {id=ID:LiXinlei-RSC-62565-1530181919410-4:60:1,started=true} java.lang.Object@3aaa5070
2018-06-28 18:41:10.185 DEBUG 18140 --- [enerContainer-1] o.springframework.jms.core.JmsTemplate   : Sending created message: ActiveMQTextMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = false, droppable = false, jmsXGroupFirstForConsumer = false, text = Reply - pineapple_error}
2018-06-28 18:41:10.185 DEBUG 18140 --- [enerContainer-1] o.s.j.connection.JmsTransactionManager   : Participating transaction failed - marking existing transaction as rollback-only
2018-06-28 18:41:10.185 DEBUG 18140 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer  : Rolling back transaction because of listener exception thrown: org.springframework.jms.listener.adapter.ListenerExecutionFailedException: Listener method 'public void com.example.demo.service.CustomerService.handle(java.lang.String)' threw exception; nested exception is java.lang.RuntimeException: some Data error.
2018-06-28 18:41:10.187  WARN 18140 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer  : Execution of JMS message listener failed, and no ErrorHandler has been set.
null

实验2结论:

  • 受JmsTransactionManager的控制,因监听到MQ中消息而被调用的service层的handle方法,出错后将不再重试7次,直接rollback;

第二部分 - 代码实现

  • service代码
package com.example.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class CustomerService {

    private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);

    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private PlatformTransactionManager transactionManager;

    @JmsListener(destination = "customer:msg2:new", containerFactory = "msgFactory")
    public void handle2(String msg) {
        logger.debug("Get JMS message2 to from customer:{}", msg);
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            String reply = "Replied-2 - " + msg;
            jmsTemplate.convertAndSend("customer:msg:reply", reply);
            if (!msg.contains("error")) {
                transactionManager.commit(status);
            } else {
                transactionManager.rollback(status);
            }
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    private void simulateError() {
        throw new RuntimeException("some Data error.");
    }

}

注:实验结果同第一部分,略

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容