使用rabbitmq发送消息不是字符串而是结构体

use*_*534 5 rabbitmq

我读了教程,RabbitMQ是一个消息代理,消息是一个字符串。是否有任何想法将消息定义为类或结构?这样我就可以定义我的消息结构。

rob*_*olf 5

消息作为字节流发送,因此您可以将任何可序列化的对象转换为字节流并发送它,然后在另一端将其反序列化。

将其放入消息对象中,并在发布消息时调用它:

    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; 
    }
Run Code Online (Sandbox Code Playgroud)

将其放入消息对象中并在消息被消费时调用它:

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;     
}
Run Code Online (Sandbox Code Playgroud)