【问题标题】:RabbitMQ for Java: how to send multiple values?RabbitMQ for Java:如何发送多个值?
【发布时间】:2016-04-30 17:07:57
【问题描述】:

这是RabbitMQ for Java: how to send multiple float values?的扩展

我想发送 3 个不同的类作为参数,而不是 3 个浮点参数,并且我想使用 JSon 协议。

服务器是用 C# 编写的。因此我解码了服务器端的 JSon 字符串方法。

基本上其他帖子提供的浮动解决方案如下:

final ByteBuffer buf = ByteBuffer.allocate(12)  // 3 floats
    .putFloat(f1).putFloat(f2).putFloat(f3);    // put them; .put*() return this
channel.basicPublish(buf.array());              // send

这将以大端(默认网络顺序和 Java 使用的顺序)写入浮点数。

在接收方,你会这样做:

// delivery is a QueuingConsumer.Delivery

final ByteBuffer buf = ByteBuffer.wrap(delivery.getBody());
final float f1 = buf.getFloat();
final float f2 = buf.getFloat();
final float f3 = buf.getFloat();

我想将 Car、Airplane、Boat 类作为 JSON 格式从 Java 发送到 C#

【问题讨论】:

    标签: java c# json rabbitmq


    【解决方案1】:

    我假设 Car、Airplane 和 Boat 是简单的 JavaBeans 类,并且它们的字段成员映射 json 合约。

    您可以使用 json 编解码器将对象序列化为 JSON。例如,您可以使用Jacksongson

    类:

    class Car {
        private String model;
        public String getModel(){};
        public void setModel(String model){...};            
    }
    class Airplane {
        private String model;
        public String getModel(){};
        public void setModel(String model){...};            
    }
    class Boat {
        private String model;
        public String getModel(){};
        public void setModel(String model){...};            
    }
    

    该示例将使用 Jackson 并将输出如下结构: {"car":{"model":"xxx"},"boat":{"model":"xxx"}, ,"airplane":{"model":"xxx"}}

    // Create the jsonFactory with an object mapper to serialize object to json
    JsonFactory jsonFactory = new JsonFactory(new ObjectMapper());
    
    // Create the byte array output stream
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
    // Create the json generator 
    JsonGenerator generator = jsonFactory.createGenerator(outputStream);
    
    // Write the start object, ie. {}
    generator.writeStartObject();
    // Write the car "car":{}
    generator.writeObjectField("car" , car);
    // Write the car "boat":{}
    generator.writeObjectField("boat" , boat);
    // Write the car "airplane":{}
    generator.writeObjectField("airplane" , airplane);
    // Close the object
    generator.writeEndObject();
    // And the generator
    generator.close();
    
    // Convert the byte array stream to a byte array and publish the message
    channel.basicPublish(outputStream.toByteArray());   
    

    如果你有一个 JavaBeans 或一个包装了这 3 个类的映射,那么代码可能会更简单:

    ObjectMapper mapper = new ObjectMapper();
    byte[] bur = mapper.writeValueAsBytes(wrapper);
    channel.basicPublish(outputStream.toByteArray());   
    

    最后,在 c# 方面,您应该创建相同的类和deserialize them

    您可以使用一些 json 到 java/c# 生成器,例如。 jsonschema2pojo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      相关资源
      最近更新 更多