[英]Convert java POJO to Avro schema object then send to kafka server by KafkaTemplate
In our restAPI we will get a complex JSON payload and map it into a POJO.在我们的 restAPI 中,我们将获得一个复杂的 JSON 有效负载并将其映射到 POJO。 And based on the avro avsc schema file I use avro-maven-plugin to generate some avro schema class.
并基于 avro avsc 模式文件,我使用 avro-maven-plugin 生成一些 avro 模式类。
My question is when we send message to kafka and schema registry by using KafkaTemplate, we need to send with avro schema object.我的问题是,当我们使用 KafkaTemplate 向 kafka 和模式注册表发送消息时,我们需要使用 avro 模式对象发送。 We can't manually map values from the payload request object into the avro schema object due to the huge number of fields.
由于字段数量众多,我们无法手动将负载请求对象中的值映射到 avro 模式对象中。
Two steps to convert any pojo class to avro genric record将任何 pojo 类转换为 avro genric 记录的两个步骤
Using jackson/avro, to convert the pojo into bytes with Avro Mapper.使用 jackson/avro,通过 Avro Mapper 将 pojo 转换为字节。
Using Avro GenericDatumReader to read it as Generic Record.使用 Avro GenericDatumReader 将其作为通用记录读取。
public class AvroConverter{
public static GenericRecord convertToGenericRecord(String schemaPath, SomeClass someObject){
Schema schema = new Schema.Parser().setValidate(true).parse(new ClassPathResource(schemaPath).getFile());
AvroSchema avSchema = new AvroSchema(schema);
ObjectWritter writter = new AvroMapper().writer(avSchema);
final byte[] bytes = objectWriter.writeValueAsBytes(someObject);
GenericDatumReader<Object> genericRecordReader = new GenericDatumReader<>(avSchema);
return (GenericRecord) genericRecordReader.read(null, DecoderFactory.get().binaryDecoder(bytes, null));
}
}
Gradle Dependency Gradle 依赖
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-avro'
While doing serialization, you may face issues.在进行序列化时,您可能会遇到问题。 For that, you have to configure the avro mapper properties
为此,您必须配置 avro 映射器属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.