Spring整合ActiveMQ-序列化的 Java对象

JMS定义了五种不同的消息正文格式,以及调用的消息类型,允许你发送并接收以一些不同形式的数据,提供现有消息格式的一些级别的兼容性。

· StreamMessage -- Java原始值的数据流

· MapMessage--一套名称-值对

· TextMessage--一个字符串对象

· ObjectMessage--一个序列化的 Java对象

· BytesMessage--一个未解释字节的数据流

1.发送者

  

package com.tech.gps.util;

import org.springframework.jms.core.JmsTemplate;

import com.tech.gps.model.Bus;

 
public class MessageSender {  
    
    private JmsTemplate jmsTemplate;  
  
    public void sendMessage(Bus bus){  
       
        jmsTemplate.convertAndSend(bus);  
    }

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}  
 
}  
 
2.消息转化

   

package com.tech.gps.util;

import java.io.Serializable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TopicPublisher;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import com.tech.gps.model.Bus;

public class MessageConvertForSys implements MessageConverter {  
    
    public Message toMessage(Object object, Session session)  
            throws JMSException, MessageConversionException {  
    	
        System.out.println("sendMessage:"+object.toString());  
        ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
        msg.setObject((Serializable) object);
        return msg; 
    }  
     
    public Object fromMessage(Message message) throws JMSException,  
            MessageConversionException {  
    	 
    	 Bus bus = null;
    	 if(message instanceof ActiveMQObjectMessage){
             ActiveMQObjectMessage aMsg = (ActiveMQObjectMessage) message; 
             bus=(Bus) aMsg.getObject();
         }
		return bus;  
    }
 
} 
3.接受消息

   

package com.tech.gps.util;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import com.tech.gps.model.Bus;

 

public class MessageReceiver implements MessageListener {  
      
    public void onMessage(Message m) {  
    	
    	 Bus bus= new Bus();
    	 if(m instanceof ObjectMessage){
             ObjectMessage objectMessage=(ObjectMessage) m;
         try {
        	 
        	 bus=(Bus) objectMessage.getObject();
             String busNo = bus.getBusNO();
        	 String xpoint = bus.getxPoint();
        	 String yPoint = bus.getyPoint();
        	 System.out.println("车编号:"+busNo+"  X:"+xpoint+"  Y:"+yPoint);
         } catch (JMSException e) {
             e.printStackTrace();
         }
         }
    	 
    }

	 
}  


源码下载地址: http://download.csdn.net/detail/allen_gang/6642167

你可能感兴趣的:(java)