我有一个围绕经纪人设计的系统,这样我的生产者使用Java,而消费者使用Go。

我正在使用apache-pulsar作为我的经纪人

Java-生产者

将MessageJava类转换为字节数组,然后再将其发送给pulsar :MessageJava类的对象调用同一类中定义的getBytes()方法将其转换为byte [],然后将该数组发送给apache-pulsar

class MessageJava {
  String   id;
  int      entityId;
  Date     timestamp;

  public byte[] getBytes() throws Exception{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(this);
    oos.flush();
    return bos.toByteArray();
  }
}

我的使用者是用Go语言编写的。

转到-消费者

从pulsar读取字节数组,并使用ConvertAfterReceiving方法[定义如下]将其转换为MessageGo结构,我正在使用gob解码:
type MessageGo struct {
    Id            string
    EntityId      int
    Timestamp     time.Time
}

func ConvertAfterReceiving(msg pulsar.Message) *MessageGo {
    payload := msg.Payload()
    messageBytes := bytes.NewBuffer(payload)
    dec := gob.NewDecoder(messageBytes)

    var message MessageGo
    err := dec.Decode(&message)
    if err != nil {
        logging.Log.Error("error occurred in consumer while decoding message:", err)
    }
    return &message
}

问题是我无法解码byte []并将其转换为MessageGo结构。它显示错误编码的无符号整数超出范围

我试过将MessageJava.entityId更改为short / long,将MessageGo.EntityId更改为int8 / int16 / int32 / int64 / uint8 / uint16 / uint32 / uint64 [所有排列],但都徒劳。

最佳答案

Java ObjectOutputStream和Go Decoder不会讲相同的语言,即使在基础上它们都由字节组成。 “这些单词”和“этислова”由行组成的方式相同,但是知道一个不会让您知道另一个。
ObjectOutputStream将对象转换为Java ObjectInputStream可以读取的形式,而Go Decoder期望使用Go Encoder创建的格式的数据。

他们需要的是一种都像JSON一样讲的语言,JavaGo都知道如何使用。然后,您无需将对象直接序列化为字节,而是将其转换为字符串表示形式,发送该字符串的字节,然后在Go中将该字符串转换为所需的结构。

关于java - 将Java字节数组转换为Go结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61140082/

10-11 22:26
查看更多