对spring了解的不够精通,这两天在解决jms异常的过程中发现,spring中提供了jmsTrasactionManager,同样实现了事务管理接口。这样用自动的拦截器,就可以象数据库一样自动控制事务。在同时配置了JMS和数据库事务的时候,两者同时有效。这样系统的消息和数据库事务就轻量级的一致了!
数据库的spring配置参见:http://steeven.cnblogs.com/archive/2005/06/14/174410.html
jms部分如下:
<bean id="remoteJmsConnectionFactory"
class="org.activemq.ActiveMQConnectionFactory">
<property name="useEmbeddedBroker">
<value>true</value>
</property>
<property name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>
<bean id="jmsTM"
class="org.springframework.jms.connection.JmsTransactionManager">
<property name="connectionFactory">
<ref bean="remoteJmsConnectionFactory" />
</property>
</bean>
<bean id="jmsTransactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="jmsTM" />
</property>
<property name="transactionAttributeSource">
<bean
class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean
class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor">
<ref bean="jmsTransactionInterceptor" />
</property>
</bean>
<bean id="destResolver"
class="test.message.EnumDestinationResolver" />
<!-- for send jms to remote server -->
<bean id="remoteJmsTemplate"
class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="remoteJmsConnectionFactory" />
</property>
<property name="destinationResolver">
<ref local="destResolver" />
</property>
</bean>
class="org.activemq.ActiveMQConnectionFactory">
<property name="useEmbeddedBroker">
<value>true</value>
</property>
<property name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>
<bean id="jmsTM"
class="org.springframework.jms.connection.JmsTransactionManager">
<property name="connectionFactory">
<ref bean="remoteJmsConnectionFactory" />
</property>
</bean>
<bean id="jmsTransactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref bean="jmsTM" />
</property>
<property name="transactionAttributeSource">
<bean
class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean
class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor">
<ref bean="jmsTransactionInterceptor" />
</property>
</bean>
<bean id="destResolver"
class="test.message.EnumDestinationResolver" />
<!-- for send jms to remote server -->
<bean id="remoteJmsTemplate"
class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="remoteJmsConnectionFactory" />
</property>
<property name="destinationResolver">
<ref local="destResolver" />
</property>
</bean>
应用程序很简单
@Transactional
public class TestServiceImpl implements TestService {
public void someMethod() {
getJmsTemplate().send(someMessage);
}
}