Spring整合ActiveMQ-序列化的 Java物件
阿新 • • 發佈:2019-02-06
JMS定義了五種不同的訊息正文格式,以及呼叫的訊息型別,允許你傳送並接收以一些不同形式的資料,提供現有訊息格式的一些級別的相容性。
· StreamMessage -- Java原始值的資料流
· MapMessage--一套名稱-值對
· TextMessage--一個字串物件
· ObjectMessage--一個序列化的 Java物件
· BytesMessage--一個未解釋位元組的資料流
1.傳送者
2.訊息轉化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; } }
3.接受訊息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; } }
原始碼下載地址:http://download.csdn.net/detail/allen_gang/6642167package 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(); } } } }