第一部分 - 注解实现
配置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
- 请求:
http://localhost:6666/api/customer/message1/direct?msg=apple_error - 服务器日志:
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
- 查询customer:msg:reply队列:
http://localhost:6666/api/customer/message - 查询结果:
null
实验1结论:
- 由于受JmsTransactionManager的控制,直接从controller调service的handle方法也将收到事务的控制;
实验2 - service的handle方法因监听到MQ中的消息而被调用
- 请求:
http://localhost:6666/api/customer/message1/listen?msg=pineapple_error - 服务器日志
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.
- 查询customer:msg:reply队列:
http://localhost:6666/api/customer/message - 查询结果:
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.");
}
}
注:实验结果同第一部分,略