首页 文章

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

提问于
浏览
0

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

我使用python和scala将avro编码消息发送到kafka . 我有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)

Avro架构看起来像

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

}

我能够在scala中的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)

scala avro使用者也不了解python 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中保持一致?任何指针都会很棒

1 回答

  • 1

    我在python中使用二进制编码器而在Scala中没有任何东西 . 只需改变一行

    val recordInjection = GenericAvroCodecs[GenericRecord](schema)
    

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

    我希望其他人认为它有用 . python代码中不需要更改

相关问题