4

我阅读了教程,RabbitMQ 是一个消息代理,消息是一个字符串。是否知道消息被定义为类或结构?所以我可以定义我的消息结构。

4

1 回答 1

4

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

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

    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;     
}
于 2012-07-26T05:08:49.857 回答