Hakob Hakobyan
Hakob Hakobyan

Reputation: 1131

How to consume messages from Kafka by type

I'm new to kafka and have some questions about it. I have configured a kafka consumer to consume messages from topic and I'm having different types of events coming to the topic. f.e.

class Event {
    String type;
    Object event;
}

I want to configure different kafka listeners to consume different types of events. I see two ways of doing it like consuming event in String(json) format and the converting to event object and switching between types and doing business logic, or configuring different kafka listener factory

    public ConcurrentKafkaListenerContainerFactory<String, String> businessEventStreamListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setRecordFilterStrategy(consumerRecord -> !consumerRecord.value().contains("typeOfObjectIWantToConsume"));
        return factory;
    }

So the first approach is not SOLID and for the second one I need to create a lot of factory classes. Is there any way to do this more elegantly?

Upvotes: 2

Views: 1146

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121560

Well, this kind of business requirements was really a reason why we have introduced a @KafkaHandler.

See more info in docs: https://docs.spring.io/spring-kafka/docs/current/reference/html/#class-level-kafkalistener.

Upvotes: 3

Related Questions