[英]Sending object using spring boot JMS
我做了2個課程:1個發送和1個接收。 目前,我只能發送一個基本字符串,並且效果很好
寄件人
@Component
public class Sender {
@Autowired
private JmsTemplate jmsTemplate;
//Script must be serializable
public void testSend(/*Script*/String message)
{
jmsTemplate.convertAndSend("my-destination", message);
}
}
接收器
@Component
public class Receiver {
@Autowired
private ConfigurableApplicationContext context;
@JmsListener(destination = "my-destination")
public void receive(String message) {
System.out.println(message);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.close();
}
}
我不能在這里實現適當的代碼,如果有人可以告訴我該怎么做,我將不勝感激
除了發送復雜的Java對象(可序列化)外,我幾乎會做同樣的事情。 並且接收器類應該能夠識別對象的類。
您可以直接創建一個ByteMessage並序列化您的對象(該對象必須可序列化):
this.jmsTemplate.send("my-destination", new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
final ObjectOutputStream oOut = new ObjectOutputStream(bOut);
oOut.writeObject(_object); // where object is the object to serialize
bytes[] data = bOut.toByteArray();
return session.createByteMessage(data);
}
});
和
@JmsListener(destination = "my-destination")
public void receive(Message message) {
final BytesMessage message = (BytesMessage) _message;
final byte[] array = new byte[Long.valueOf(message.getBodyLength()).intValue()];
message.readBytes(array);
final ByteArrayInputStream bIn = new ByteArrayInputStream(_bytes);
final ObjectInputStream oIn = new ObjectInputStream(bIn);
Object obj = oIn.readObject(); // the deserialized object
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.