JMS Apache ActiveMQ使用(2)
下面就进行程序开发,没得说,当然是spring了
使用spring开发JMS比较简单,直接使用的是JmsTemplate,需要几个相关对象。
ConnectionFactory:创建与ActiveMQ连接的工厂类
Destination:目标Topic或Queue
MessageConverter:在Java POJO和JMS Message进行转换
关于JMS的其他接口如Session,MessageProducer/MessageConsumer都是在JmsTemplate内部处理,不需要开发关注具体细节。
首先配置分别针对Topic和Queue的JmsTemplate(其实发送和接受消息代码中不需要关心是Topic还是Queue,JMS 1.1标准对于两者在客户端的处理已经可以通用了)
spring-jms.xml
<?xml version="1.0" encoding="GBK"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN""http://www.springframework.org/dtd/spring-beans-2.0.dtd"><beans><bean id="jmsFactory" value="failover:(tcp://localhost:61616)"/><property name="transportListener"><bean ref="jmsFactory" /><property name="defaultDestination" ref="queueDestination"/><property name="messageConverter" ref="messageConvert"/> </bean><bean id="topicTemplate" ref="jmsFactory" /><property name="defaultDestination" ref="topicDestination"/><property name="messageConverter" ref="messageConvert"/> </bean></beans>
import org.springframework.jms.support.converter.MessageConversionException;import org.springframework.jms.support.converter.MessageConverter;import javax.jms.JMSException;import javax.jms.MapMessage;import javax.jms.Message;import javax.jms.Session;import java.util.Date;/** * User: bloodwolf_china * Date: 2008-6-24 * Time: 15:20:42 * Descript: */public class VivaMessageConvert implements MessageConverter {public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {MapMessage msg = session.createMapMessage();VivaUserRegisterMessage registerMessage = (VivaUserRegisterMessage) object;msg.setLong("RegisterTime",registerMessage.getRegisterTime().getTime());msg.setInt("UserId",registerMessage.getUserId());msg.setString("Tel",registerMessage.getTel());return msg; }public Object fromMessage(Message message) throws JMSException, MessageConversionException {MapMessage msg = (MapMessage) message;VivaUserRegisterMessage registerMessage = new VivaUserRegisterMessage();registerMessage.setRegisterTime(new Date(msg.getLong("RegisterTime")));registerMessage.setUserId(msg.getInt("UserId"));registerMessage.setTel(msg.getString("Tel"));return registerMessage;}}