ConcurrentMessageListenerContainer不是并发的

问题描述 投票:1回答:1

我正在尝试创建一个多线程侦听器,但所有消息都在同一个线程中执行。运行时,线程ID总是相同的,即使KafkaListerContainerFactory(正确地)是我实例化的那个。如果我几乎同时发送7条消息,我希望前三个同时处理,然后是后三个同时处理,然后是最后一个。我看到的是第一个完成的过程,然后是第二个,然后是第三个,等等。我误解了什么,或者只是错误配置?

这是我的倾听者:

@Component
public class ExampleKafkaController {
    Log log = Log.getLog(ExampleKafkaController.class);

    @Autowired
    private KafkaListenerContainerFactory kafkaListenerContainerFactory;

    @KafkaListener(topics = "${kafka.example.topic}")
    public void listenForMessage(ConsumerRecord<?, ?> record) {
        log.info("Got record:\n" + record.value());
        System.out.println("Kafka Thread: " + Thread.currentThread());
        System.out.println(kafkaListenerContainerFactory);

        log.info("Waiting...");
        waitSleep(10000);

        log.info("Done!");
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${kafka.example.topic}")
    public String topic;    

    public void send(String payload) {
        log.info("sending payload='" + payload + "' to topic='" + topic + "'");
        kafkaTemplate.send(topic, payload);
    }

    private void waitSleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

这是我的应用程序与新配置:

@SpringBootApplication
@ComponentScan("net.reigrut.internet.services.example.*")
@EntityScan("net.reigrut.internet.services.example.*")
@EnableKafka
@Configuration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired 
    ConsumerFactory<Integer,String> consumerFactory;

    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory);
        factory.setConcurrency(3);
        System.out.println("===========>" + consumerFactory);
        System.out.println(factory);
        return factory;
    }
}
spring-boot apache-kafka spring-kafka
1个回答
7
投票

使用Kafka,并发性仅限于主题中的分区数。如果只有一个分区,则只会在一个线程上接收消息,而不管容器的并发设置如何。

您应该将分区数设置为大于或等于所需的并发数。如果分区数大于并发数,则分区将分布在使用者线程中。

组中只有一个使用者可以从分区中使用。

© www.soinside.com 2019 - 2024. All rights reserved.