我们的项目有scala和python代码,我们需要向kafka发送/使用avro编码的消息。
我使用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 = “阿夫罗/ 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中保持一致?任何指针都会很棒
答案 0 :(得分:1)
我在python中使用二进制编码器而在Scala中没有使用任何内容。只需从
更改一行val recordInjection = GenericAvroCodecs[GenericRecord](schema)
到
val recordInjection = GenericAvroCodecs.toBinary[GenericRecord](schema)
我希望其他人觉得它很有用。 python代码中不需要进行任何更改