【问题标题】:using rabbitmq to send a message not string but struct使用rabbitmq发送消息不是字符串而是结构
【发布时间】:2012-07-26 01:10:09
【问题描述】:

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

【问题讨论】:

    标签: rabbitmq


    【解决方案1】:

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

    把这个放在消息对象中,在消息发布的时候调用:

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

    【讨论】:

    • 您实际上可以使用 JSON.NET 轻松地将内容序列化/反序列化为 JSON。
    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2013-03-04
    • 2018-08-16
    • 2017-08-17
    相关资源
    最近更新 更多