我们的项目有scala和python代码,我们需要向kafka发送/使用avro编码的消息。
我正在使用python和scala向kafka发送avro编码消息。我有scala代码中的producer,它使用twitter双射库发送avro编码的消息,如下所示:
val resourcesPath = getClass.getResource("/avro/url_info_schema.avsc")
val schemaFile = scala.io.Source.fromURL(resourcesPath).mkString
val schema = parser.parse(schemaFile)
val recordInjection = GenericAvroCodecs[GenericRecord](schema)
val avroRecord = new GenericData.Record(schema)
avroRecord.put("url_sha256", row._1)
avroRecord.put("url", row._2._1)
avroRecord.put("timestamp", row._2._2)
val recordBytes = recordInjection.apply(avroRecord)
kafkaProducer.value.send("topic", recordBytes)
avro架构看起来像
{
"namespace": "com.rm.avro",
"type": "record",
"name": "url_info",
"fields":[
{
"name": "url_sha256", "type": "string"
},
{
"name": "url", "type": "string"
},
{
"name": "timestamp", "type": ["long"]
}
]
}
我能够在斯卡拉的《Kafka康苏美尔》中成功地解码它
val resourcesPath = getClass.getResource("/avro/url_info_schema.avsc")
val schemaFile = scala.io.Source.fromURL(resourcesPath).mkString
kafkaInputStream.foreachRDD(kafkaRDD => {
kafkaRDD.foreach(
avroRecord => {
val parser = new Schema.Parser()
val schema = parser.parse(schemaFile)
val recordInjection = GenericAvroCodecs[GenericRecord](schema)
val record = recordInjection.invert(avroRecord.value()).get
println(record)
}
)
}
但是,我无法在python中解码消息,我得到以下异常
'utf8' codec can't decode byte 0xe4 in position 16: invalid continuation byte
python代码如下所示:schema\u path=“avro/url\u info\u schema.avsc”schema=avro.schema.parse(open(schema\u path.read())
for msg in consumer:
bytes_reader = io.BytesIO(msg.value)
decoder = avro.io.BinaryDecoder(bytes_reader)
reader = avro.io.DatumReader(schema)
decoded_msg = reader.read(decoder)
print(decoded_msg)
另外,scala avro使用者不理解python avro生产者消息。我有个例外。python avro producer如下所示:
datum_writer = DatumWriter(schema)
bytes_writer = io.BytesIO()
datum_writer = avro.io.DatumWriter(schema)
encoder = avro.io.BinaryEncoder(bytes_writer)
datum_writer.write(data, encoder)
raw_bytes = bytes_writer.getvalue()
producer.send(topic, raw_bytes)
如何在python和scala之间保持一致?任何指点都很好
1条答案
按热度按时间oprakyz71#
我在python中使用二进制编码器,而在scala中没有。只是换了一行
至
我希望其他人觉得有用。在python代码中不需要更改