我阅读了教程,RabbitMQ是一个消息代理,消息是一个字符串。 有没有想过消息被定义为类或结构?所以我可以定义我的消息结构。
答案 0 :(得分:3)
消息作为字节流发送,因此您可以将任何可序列化的对象转换为字节流并发送,然后在另一侧反序列化。
将它放在消息对象中,并在消息发布时调用它:
public byte[] toBytes() {
byte[]bytes;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try{
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.flush();
oos.reset();
bytes = baos.toByteArray();
oos.close();
baos.close();
} catch(IOException e){
bytes = new byte[] {};
Logger.getLogger("bsdlog").error("Unable to write to output stream",e);
}
return bytes;
}
将它放在消息对象中,并在消息消耗时调用它:
public static Message fromBytes(byte[] body) {
Message obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (body);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = (Message)ois.readObject();
ois.close();
bis.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}