在跨 Python 和 Go 语言实现序列化和反序列化时,开发者可能遇到“无法解析无效的有线格式数据”错误。这通常是因为两种语言中使用的序列化库不匹配。具体来说,如果 Python 使用 Confluence 序列化器,则 Go 也必须使用相同的库及其架构注册表。Confluence 提供了一个 Go 客户端,可用于与 Python 序列化器进行交互,从而解决此错误。
我正在尝试在 python 中序列化并在 golang 中解组,但遇到错误。
错误消息——“无法解析无效的有线格式数据”。
代码配置 --
python代码 --
schema_registry_client = schemaregistryclient({'url': 'http://localhost:8082'})
protobuf_serializer = protobufserializer(user_attributes_pb2.userproperties,
schema_registry_client,
{'use.deprecated.format': true})
producer_conf = {'bootstrap.servers': 'localhost:9092', 'key.serializer': stringserializer('utf_8'), 'value.serializer': protobuf_serializer}
producer = serializingproducer(producer_conf)
producer.poll(0.0)
########## add an address #########
promptforaddress(user_attr)
producer.produce(topic=topic, key=str(uuid4()), value=user_attr)
producer.flush()
golang代码 --
Brokers: []string{brokerAddress},
Topic: topic,
GroupID: "test-consumer-group",
Logger: l,
})
for {
msg, err := r.ReadMessage(ctx)
user := &pb.UserProperties{}
err = proto.Unmarshal(msg.Value, user)
// client.Query() NewKey(Namespace, Set, user.Id)
if err != nil {
log.Fatal(err)
}
fmt.Printf("\n%s\n", proto.Message(user))
fmt.Printf("\n%v\n", user)
if err != nil {
panic("could not read message " + err.Error())
}
// after receiving the message, log its value
fmt.Println("received: ", string(msg.Value))
}
两种语言的 proto 文件相似。
正确答案
由于您使用 Confluence Python 序列化器及其架构注册表,因此您需要在 Go 中执行相同的操作,而不能仅使用普通的 Protobuf 反序列化。
Confluence 还维护一个可供您使用的 Go 客户端。 Protobuf 示例 - https://github.com/confluentinc/confluent-kafka-go/blob/master/examples/protobuf_consumer_example/protobuf_consumer_example.go
我不确定 use.deprecated.format 对 Python 的作用,但 Go 可能不接受
今天关于《序列化和反序列化的跨语言实现》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
