using rabbitmq to send a message not string but struct

孤街浪徒 提交于 2019-12-30 06:55:15

问题


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.


回答1:


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;     
}


来源:https://stackoverflow.com/questions/11660979/using-rabbitmq-to-send-a-message-not-string-but-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!