首页 > 解决方案 > Spring KafkaListener:如何知道它何时准备就绪

问题描述

我有一个简单的 Spring Boot 应用程序,它从 Kafka 读取并写入 Kafka。我写了一个SpringBootTest使用 anEmbeddedKafka来测试所有这些。

主要问题是:有时测试失败是因为测试过早发送Kafka消息。这样,在 Spring 应用程序(或者KafkaListener准确地说)准备好之前,消息就已经写入 Kafka。由于侦听器从latest偏移量读取(我不想为我的测试更改任何配置 - 除了 bootstrap.servers),它不会收到该测试中的所有消息。

有谁知道我如何在测试中知道它KafkaListener已准备好接收消息?

我能想到的唯一方法是等到/health可用,但我不知道我是否可以确定这意味着KafkaListener要准备好。

任何帮助是极大的赞赏!

此致。

标签: springspring-bootapache-kafkaspring-kafkaspring-kafka-test

解决方案


如果你有一个KafkaMessageListenerContainer实例,那么它很容易使用org.springframework.kafka.test.utils.ContainerTestUtils.waitForAssignment(Object container, int partitions)

https://docs.spring.io/spring-kafka/api/org/springframework/kafka/test/utils/ContainerTestUtils.html

例如,在您的测试设置中调用ContainerTestUtils.waitForAssignment(container, 1);将阻塞,直到容器分配了 1 个分区。


推荐阅读