Avro Kafka 在 scala 和 Python 之间的转换问题



我们的项目同时有scala和python代码,我们需要向kafka发送/使用avro编码的消息。

我正在使用python和scala向kafka发送avro编码消息。我在scala代码中有生产者,它使用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)

阿夫罗模式看起来像

{
  "namespace": "com.rm.avro",
  "type": "record",
  "name": "url_info",
  "fields":[
     {
        "name": "url_sha256", "type": "string"
     },
     {
        "name": "url",  "type": "string"
     },
     {
        "name": "timestamp", "type": ["long"]
     }
 ]

}

我能够在 KafkaConsumer 中成功地解码它

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_path="avro/url_info_schema.avsc" schema = avro.schema.parse(open(schema_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)

此外,python avro 生产者的消息不被 scala avro 消费者理解。我在那里得到一个例外。Python Avro 生产者如下所示:

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 中保持一致?任何指针都会很棒

我在python中使用了二进制编码器,而在Scala中使用了任何东西。只需要从

val recordInjection = GenericAvroCodecs[GenericRecord](schema)

val recordInjection = GenericAvroCodecs.toBinary[GenericRecord](schema)

我希望其他人觉得它有用。无需在 python 代码中进行任何更改

最新更新