【问题标题】:Embedded kafka producer test嵌入式 kafka 生产者测试
【发布时间】:2019-09-18 05:46:48
【问题描述】:

我正在编写集成测试来测试 kafka 生产者。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {kafkaProducerConfig.class, KafkaProducerIT.InnerConfig.class})
@EnableConfigurationProperties(KafkaProducerInfo.class)
@ComponentScan(basePackages = "...")
public class KafkaProducerIT {

    @ClassRule
    public static EmbeddedKafkaRule embeddedKafka = new EmbeddedKafkaRule(1, true, "testtopic");

    @Autowired
    CustomKafkaProducer<String, String> KafkaProducer;

    @Autowired
    KafkaController kafkaController;

    @Test
    public void whenSendMessage_thenConsumeIt() throws InterruptedException {
        KafkaProducer.produceMessageToKafkaTopic("ahahahwow", "testtopic");
        kafkaController.countDownLatch.await();
    }

    @Configuration
    public static class InnerConfig {

        @Bean
        public KafkaListenerContainerFactory<?> kafkaListenerContainerFactory(ConsumerFactory<String, Object> replyConsumerFactory) {
            ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
            factory.setConsumerFactory(replyConsumerFactory);
            factory.setBatchListener(true);
            return factory;
        }

        @Bean
        KafkaController kafkaController() {
            return new KafkaController();
        }

    }

    public static class KafkaController {

        CountDownLatch countDownLatch = new CountDownLatch(1);

        @KafkaListener(topics = "testtopic")
        public void listen(final String payload) {
            countDownLatch.countDown();
        }
    }

}

我想向主题发送消息,使用KafkaControllerCountDownLatch 阅读。 我遇到的问题是CountDownLatch 永远不会被触发并且测试只是挂在await 上。

CustomKafkaProducer 只是一个在底层使用常规kafkaTemplate 的包装器。

附言

在调试过程中,有几种情况流进入侦听器并测试通过。所以问题与错误的主题名称等无关。

【问题讨论】:

    标签: integration-testing spring-kafka


    【解决方案1】:

    您需要为消费者设置 auto.offset.reset=earliest。默认值是最新的,因此如果消费者在记录发送后开始,则存在竞争条件。

    【讨论】:

    • 如果我错了,请纠正我 - auto.offset.reset=earliest 意味着消费者将从一开始就阅读所有发送到主题的消息?即使这些消息是在消费者开始之前发送的?
    • 没错。由于这是一个嵌入式 kafka,因此唯一的记录将是测试中发送的记录。
    猜你喜欢
    • 2021-09-07
    • 2019-05-09
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2021-07-15
    • 2020-05-21
    • 2020-06-14
    相关资源
    最近更新 更多