Consume multiple topics in one listener in spring boot kafka

。_饼干妹妹 提交于 2019-12-13 04:07:40

问题


Can anyone provide me a small example in spring boot kafka where we can consume multiple topics in one single listener class.


回答1:


application.yml

my:
    kafka:
        conf:
            groupId: myId
            topics: topic1,topicN

you listener:

@KafkaListener(groupId = "${my.kafka.conf.groupId}", topics = "#{'${my.kafka.conf.topics}'.split(',')}")
public void storeTopicsDataToMongo(
        @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
        @Header(required = false, name= KafkaHeaders.RECEIVED_MESSAGE_KEY) String key,
        @Payload(required = false) String record)
{
    log.trace(format("Received topic[%s] key[%s] payload[%s]", topic, key, record));
    //your code
}

or you can explore the @ConfigurationProperties and create the beans yourself, something like:

@Component
@ConfigurationProperties(prefix = "my.kafka.conf")
@Data //=> lombok
public class ConsumerConfigurationProperties {

    private String groupId;
    private List<String> topics;
}



回答2:


For consumers part of consumer group you can use following:

@KafkaListener(topics = "topic1,") public void listen(@Payload KafkaBinding record, MessageHeaders headers) throws ExecutionException, InterruptedException { ……… ……….. }

For consumers acting as assign you can use following:

@KafkaListener(id = “foo”,topicPartitions = { @TopicPartition(topic = “myTopic”,partitions = { “1” })}) public void listen(@Payload KafkaBinding record, MessageHeaders headers) throws ExecutionException, InterruptedException { ……… ……….. }



来源:https://stackoverflow.com/questions/52385762/consume-multiple-topics-in-one-listener-in-spring-boot-kafka

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