[英]ClassCastException on the same class deserializing from kafka stream and Avro
I have generated my Avro Java classes from Avro schema with avro-maven-plugin. 我已经使用avro-maven-plugin从Avro模式生成了Avro Java类。 I serialize my avro class to a byte array and I write it into a kafka topic.
我将avro类序列化为字节数组,并将其写入kafka主题。
Then I have a kafka stream that tries to manipulate avro data to do something. 然后,我有一个kafka流,尝试操纵avro数据以执行某些操作。 During the deserialization process I get a ClassCastExcetion from the same class.
在反序列化过程中,我从同一类中获得ClassCastExcetion。 I read that this problem is generated due to a different ClassLoader that Avro uses on fallback (a new instance of ClassLoader).
我读到这个问题是由于Avro在回退时使用了另一个ClassLoader(ClassLoader的新实例)而产生的。
There is a method to force Avro to use the caller's ClassLoader or something similar? 有一种方法可以强制Avro使用调用方的ClassLoader或类似的方法?
KafkaStream properties KafkaStream属性
this.props = new Properties();
this.props.put(StreamsConfig.APPLICATION_ID_CONFIG, "test");
this.props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
this.props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
this.props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.ByteArray().getClass());
I'm using a String key and the serialized avro's byte array, then I need to manually deserialize the avro's payload. 我正在使用String键和序列化的avro的字节数组,然后需要手动反序列化avro的有效负载。 I use avro's decoder to deserialize like this:
我使用avro的解码器进行反序列化,如下所示:
AvroPayload stp = AvroPayload.fromByteBuffer(ByteBuffer.wrap(bytes));
or even like this: 甚至像这样:
AvroPayload stp = AvroPayload.getDecoder().decode(ByteBuffer.wrap(bytes));
With the first version, debugging I can see that if I remain in the avro's generated class context the byte array is correctly deserialized into the AvroPayload class. 在第一个版本的调试中,我可以看到,如果保留在avro的生成的类上下文中,则字节数组已正确反序列化为AvroPayload类。 Returning that new instance perhaps throws a
ClassCastException
返回该新实例可能会引发
ClassCastException
The only solution I found is to put as suggested the avro classes into an external jar and then import it. 我发现的唯一解决方案是按照建议将avro类放入外部jar中,然后将其导入。
It's not a good solution because it requires a lot of configuration to keep coupled your avro schemas and your generated classes, but it's the only I found. 这不是一个好的解决方案,因为它需要大量配置才能使您的avro模式和生成的类保持耦合,但这是我发现的唯一方法。
I configured a maven project that generates the avro's classes jar into a directory, without artifact version in its name, so I can always import the latest version without having to change the pom. 我配置了一个maven项目,该项目将avro的类jar生成到目录中,而名称中没有工件版本,因此我始终可以导入最新版本,而无需更改pom。
If someone will discover another solution, please post it 如果有人发现其他解决方案,请发布
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.