上文可见,JMS Native API使用起来不是特别方便。好在Spring提供了很好的JMS支持。
(一)配置ConnectionFactory
如果使用连接池的话,不要忘记activemq-pool-5.6.0.jar
<bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
<property name="connectionFactory" ref="innerConnectionFactory" />
</bean>
<bean id="innerConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
(二)配置一个Destination作为默认投递目标
<bean id="defaultDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="ztgame.amt.default.queue" />
</bean>
(三)核心JmsTemplate
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="defaultDestination" />
</bean>
(四)JMS事务
<bean id="jmsTransactionManager" class="org.springframework.jms.connection.JmsTransactionManager">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<tx:annotation-driven transaction-manager="jmsTransactionManager" />
(五)编写消息驱动Bean,两个接口实现一个即可
- javax.jms.MessageListener
- org.springframework.jms.listener.SessionAwareMessageListener
package com.ztgame.amt.jms.mdp;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.stereotype.Component;
@Component("defaultMessageHandler")
public class DefaultMessageHandler implements SessionAwareMessageListener<TextMessage> {
public void onMessage(TextMessage message, Session session)
throws JMSException {
String text = message.getText();
if (text.length() == 0) {
System.out.println("<empty>");
} else {
System.out.println(text);
}
}
}
(六)配置消息驱动Bean
<!-- Message Driven POJOs -->
<jms:listener-container connection-factory="connectionFactory">
<jms:listener destination="ztgame.amt.default.queue" ref="defaultMessageHandler" />
</jms:listener-container>
(七)编写测试代码
package junit;
import java.util.UUID;
import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.junit.Test;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@ContextConfiguration({ "classpath:spring-beans.xml", "classpath:spring-jms.xml" })
public class TestSomeService extends AbstractJUnit4SpringContextTests {
@Resource
private JmsTemplate jmsTempalte;
@Test
public void test() {
jmsTempalte.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(UUID.randomUUID().toString());
}
});
}
}