使用rabbitmq发送消息不是字符串而是结构
我阅读了教程,RabbitMQ是一个消息代理,消息是一个字符串。使用rabbitmq发送消息不是字符串而是结构,rabbitmq,Rabbitmq,我阅读了教程,RabbitMQ是一个消息代理,消息是一个字符串。 是否知道消息被定义为类或结构?因此我可以定义消息结构。消息作为字节流发送,因此您可以将任何可序列化的对象转换为字节流并发送,然后在另一端反序列化它 将其放入消息对象中,并在消息发布时调用它: public byte[] toBytes() { byte[]bytes; ByteArrayOutputStream baos = new ByteArrayOutputStream();
是否知道消息被定义为类或结构?因此我可以定义消息结构。消息作为字节流发送,因此您可以将任何可序列化的对象转换为字节流并发送,然后在另一端反序列化它 将其放入消息对象中,并在消息发布时调用它:
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;
}
将其放入message对象中,并在消息被使用时调用它:
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;
}
实际上,您可以使用JSON.NET轻松地将内容序列化/反序列化为JSON。