使用rabbitmq发送消息不是字符串而是结构 [英] using rabbitmq to send a message not string but struct
本文介绍了使用rabbitmq发送消息不是字符串而是结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看了教程,RabbitMQ 是一个消息代理,消息是一个字符串.是否知道消息被定义为类或结构?所以我可以定义我的消息结构.
i read the tutorials,RabbitMQ is a message broker,and the message is a string. is there any idea that the message is defined as a class or a struct?so i can define my message struct.
推荐答案
消息是作为字节流发送的,所以你可以将任何可序列化的对象转换成字节流发送,然后在另一端反序列化.
The message is sent as a byte stream, so you can convert any object that is serializable into a byte stream and send it, then deserialize it on the other side.
把这个放在消息对象中,在消息发布的时候调用:
put this in the message object, and call it when the message is published:
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;
}
把这个放在消息对象中,当消息被消费时调用它:
put this in the message object and call it when the message is consumed:
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;
}
这篇关于使用rabbitmq发送消息不是字符串而是结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文