Kafaka一个topic下多个消费者,只消费一条次

189 阅读1分钟

开始网上查了很多资料都没解决,后面发现是自己想多了,直接上代码 原理是首先要先手动创建topic,配置好分区数量,然后再监听对应的分区,消息之后发往带有监听的分区。

/**
 * 使用代码创建的topic
 * 三个参数意思:topic的名称;分区数量,新主题的复制因子;如果指定了副本分配,则为-1。
 */

@Configuration
public class KafakaSetParttion {

    @Bean
    public NewTopic batchTopic() {
        return new NewTopic("testTopic3", 4, (short) 1);
    }
}
@Slf4j
@Component
public class KafakTestConsumer {

    @KafkaListener(topicPartitions = {@TopicPartition(topic = "test99", partitions = {"0"})})
    public void handleSoftwareOnlineStatus(ConsumerRecord<?, ?> record) {
        String msg = (String) record.value();
        log.info("消费者1开始消费, 内容:{}", msg);
    }

    @KafkaListener(topicPartitions = {@TopicPartition(topic = "test99", partitions = {"1"})})
    public void handleSoftwareOnlineStatus2(ConsumerRecord<?, ?> record) {
        String msg = (String) record.value();
        log.info("消费者2开始消费, 内容:{}", msg);
    }
}