使用spring kafka的多个消费者

时间:2017-08-21 20:58:11

标签: spring-kafka

我希望在我的应用程序中的kafka主题上设置多个侦听器。以下是我的设置。它应该由两个组使用,但只有一个侦听器使用它。我在这里缺少什么?

@Bean
public Map<String, Object> consumerConfigs() {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, groupName);

    return props;
}

@Bean
public ConsumerFactory<String, String> consumerFactory() {
    ConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory(consumerConfigs());
    return consumerFactory;
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(100);
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

@Bean("notificationFactory")
public ConcurrentKafkaListenerContainerFactory<String, String> notificationFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(100);
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

@Bean("insertContainerFactory")
public ConcurrentKafkaListenerContainerFactory<String, String> insertContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(100);

    factory.setConsumerFactory(consumerFactory());
    return factory;
}

@KafkaListener(id = "insert_listener", topics = "${kafka.topic.readlocation}", group = "insert_listener", containerFactory = "insertContainerFactory")
public void receiveForInsert(String message) {
    locationProcessor.insertLocationData(message);
}

@KafkaListener(id = "notification_listener", topics = "${kafka.topic.readlocation}", group = "notification_listener",containerFactory="notificationFactory")
public void receiveForNotification(String message) {
    locationProcessor.processNotificationMessage(message);
}

编辑:以下是有效的代码

@KafkaListener(id = "insert_listener", topics = "${kafka.topic.readlocation}", groupId = "insert_listener")
public void receiveForInsert(String message) {
    locationProcessor.insertLocationData(message);
}  

1 个答案:

答案 0 :(得分:5)

每个人都需要不同的group.id; group属性不是group.id - 请参阅javadoc。在即将发布的1.3版本中,有一个新的groupId属性,如果存在,我们也可以将id用作一个组。

对于早期版本,每个版本都需要一个不同的消费者工厂。