我有一个kafka监听器,它正确接收数据但EventData ss = consumerRecord.value()
给出了ClassCastException。
我正在使用默认的弹簧启动设置。 我不确定它是如何正确接收消息的,当我尝试使用时,它会给出异常。
@KafkaListener(topics = "${kafka.topic.event.model.message}")
public void receive(ConsumerRecord<String, EventData> consumerRecord) throws IOException, ClassNotFoundException {
LOGGER.info("received payload='{}'", consumerRecord.value());
EventData ss = consumerRecord.value();
}
它给出了例外:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.betstars.betsyncadapter.app.kafka.message.EventData
at com.betstars.betsyncadapter.app.kafka.message.KafkaMessageListenerForEventModel.receive(KafkaMessageListenerForEventModel.java:26) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:180) ~[spring-messaging-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:112) ~[spring-messaging-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.kafka.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48) ~[spring-kafka-1.1.6.RELEASE.jar:na]
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:174) ~[spring-kafka-1.1.6.RELEASE.jar:na]
... 10 common frames omitted
答案 0 :(得分:0)
Spring Boot Apache Kafka自动配置默认使用StringDeserializer
value
:
您应该考虑为org.springframework.kafka.support.serializer.JsonDeserializer
用例使用EventData
:
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.value.default.type=com.your.EventData
虽然是春季引导2.0
。
对于以前的版本,您应使用JsonDeserializer
扩展程序:
public class EventDataJsonDeserializer extends JsonDeserializer<EventData> { }
属性:
spring.kafka.consumer.value-deserializer = com.your.EventDataJsonDeserializer
答案 1 :(得分:0)
还要仔细检查是否为消费者配置了“ properties.specific.avro.reader:true”