當試圖使用BinaryEncoder
寫入Avro對象時,我試圖發佈Avro(進入Kafka)並獲取NullPointerException
。嘗試序列化包含數組的Avro GenericRecord時發生NullPointerException
這裏是縮寫堆棧跟蹤:
java.lang.NullPointerException: null of array of com.mycode.DeeplyNestedObject of array of com.mycode.NestedObject of union of com.mycode.ParentObject
at org.apache.avro.generic.GenericDatumWriter.npe(GenericDatumWriter.java:132) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.generic.GenericDatumWriter.writeWithoutConversion(GenericDatumWriter.java:126) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:73) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:60) ~[avro-1.8.1.jar:1.8.1]
at com.mycode.KafkaAvroPublisher.send(KafkaAvroPublisher.java:61) ~[classes/:na]
....
at org.apache.avro.generic.GenericDatumWriter.write(GenericDatumWriter.java:73) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.generic.GenericDatumWriter.writeWithoutConversion(GenericDatumWriter.java:112) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.specific.SpecificDatumWriter.writeField(SpecificDatumWriter.java:87) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.generic.GenericDatumWriter.writeRecord(GenericDatumWriter.java:143) ~[avro-1.8.1.jar:1.8.1]
at org.apache.avro.generic.GenericDatumWriter.writeWithoutConversion(GenericDatumWriter.java:105) ~[avro-1.8.1.jar:1.8.1]
... 55 common frames omitted
這裏就是異常發生在我的代碼的發送方法:
private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get();
private static final SpecificDatumWriter<ParentObject> PARENT_OBJECT_WRITER = new SpecificDatumWriter<>(ParentObject.SCHEMA$);
public void send(ParentObject parentObject) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
binaryEncoder = ENCODER_FACTORY.binaryEncoder(stream, binaryEncoder);
PARENT_OBJECT_WRITER.write(parentObject, binaryEncoder); // Exception HERE
binaryEncoder.flush();
producer.send(new ProducerRecord<>(topic, stream.toByteArray()));
} catch (IOException ioe) {
logger.debug("Problem publishing message to Kafka.", ioe);
}
}
在架構中,NestedObject
包含DeeplyNestedObject
陣列。我已經做了足夠的調試,看看NestedObject
確實包含一個DeeplyNestedObject
的數組或者一個空數組(如果不存在的話)。下面是模式的相關部分:
[ { "namespace": "com.mycode.avro"
, "type": "record"
, "name": "NestedObject"
, "fields":
[ { "name": "timestamp", "type": "long", "doc": "Instant in time (milliseconds since epoch)." }
, { "name": "objs", "type": { "type": "array", "items": "DeeplyNestedObject" }, "doc": "Elided." }
]
}
]