Deserialize kafka messages in KafkaConsumer using springboot

二次信任 提交于 2020-04-16 04:12:01

问题


I have a springboot app that listen kafka messages and convert them to object

@KafkaListener(topics = "test", groupId = "group_id")
public void consume(String message) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Hostel hostel = objectMapper.readValue(message, Hostel.class);
}

I woder if it is possible to do ti directly

@KafkaListener(topics = "test", groupId = "group_id")
public void consume(Hostel hostel) throws IOException { 
}

回答1:


You can do it using spring-kafka. But then you need to use a custom deserializer (or a JsonDeserializer) in the container factory

@KafkaListener(topics = "test", groupId = "my.group", containerFactory = "myKafkaFactory")
fun genericMessageListener(myRequest: MyRequest, ack: Acknowledgment) {
//do Something with myRequest
ack.acknowledge()
}

Your ContainerFactory will look something like

@Bean
fun myKafkaFactory(): ConcurrentKafkaListenerContainerFactory<String, MyRequest> {
val factory = ConcurrentKafkaListenerContainerFactory<String, MyRequest>()
factory.consumerFactory = DefaultKafkaConsumerFactory(configProps(), StringDeserializer(), MyRequestDeserializer())
factory.containerProperties.ackMode = ContainerProperties.AckMode.MANUAL
return factory
}

Your Deserialiser will look like

public class MyRequestDeserializer implements Deserializer {
private static ObjectMapper objectMapper = new ObjectMapper();

@Override
public void configure(Map map, boolean b) {
}

@Override
public MyRequest deserialize(String arg0, byte[] msgBytes) {
    try {
        return objectMapper.readValue(new String(msgBytes), MyRequest.class);
    } catch (IOException ex) {
        log.warn("JSON parse/ mapping exception occurred. ", ex);
        return new MyRequest();
    }
}

@Override
public void close() {
    log.debug("MyRequestDeserializer closed");
}
}

Alternatively, you can use the default JsonDeserializer as given in spring docs



来源:https://stackoverflow.com/questions/60928034/deserialize-kafka-messages-in-kafkaconsumer-using-springboot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!