using rabbitmq to send a message not string but struct

前端 未结 1 874
一生所求
一生所求 2021-01-06 11:10

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 messa

相关标签:
1条回答
  • 2021-01-06 11:42

    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;     
    }
    
    0 讨论(0)
提交回复
热议问题