在go中使用Kafka Avro消息

时间:2016-11-11 13:20:24

标签: go apache-kafka avro kafka-consumer-api

我正在尝试以avro格式使用Kafka消息,但我无法解码Go中从avro到json的消息。

我正在使用Confluent平台(3.0.1)。例如,我生成如下的avro消息:

kafka-avro-console-producer --broker-list localhost:9092 --topic test --property value.schema='{"type":"record","name":"myrecord","fields":[{"name":"f1","type":"string"}]}'
{"f1":"message1"}
{"f1":"message2"}

现在我使用go Kafka libary消费消息:sarama。纯文本消息正常工作。必须解码Avro消息。我发现了不同的库:github.com/linkedin/goavro,github.com/elodina/go-avro

但解码后我得到一个没有值的json(两个libs):

{"f1":""}

goavro:

avroSchema := `
{"type":"record","name":"myrecord","fields":[{"name":"f1","type":"string"}]}
`
codec, err := goavro.NewCodec(avroSchema)
if err != nil {
    log.Fatal(err)
}
bb := bytes.NewBuffer(msg.Value)
decoded, err := codec.Decode(bb)
log.Println(fmt.Sprintf("%s", decoded))

去-阿夫罗:

schema := avro.MustParseSchema(avroSchema)
reader := avro.NewGenericDatumReader()
reader.SetSchema(schema)
decoder := avro.NewBinaryDecoder(msg.Value)
decodedRecord := avro.NewGenericRecord(schema)
log.Println(decodedRecord.String())

msg = sarama.ConsumerMessage

2 个答案:

答案 0 :(得分:11)

The first byte is a magic byte (0). The following 4 bytes are the avro schema ID

只有在使用Confluent模式注册表时,这才真正有用。

答案 1 :(得分:3)

刚刚发现(通过比较二进制avro消息)我必须删除消息字节数组的前5个元素 - 现在一切正常:)

message = msg.Value[5:]

也许有人可以解释原因

相关问题