我有一个 Spring Boot 测试来检查 kafka 消费者是否监听特定主题中的消息。使用
@SpringBootTest
时会触发 kafka 监听器。但我只是不想加载所有类,我只提供了这样的监听器类@SpringBootTest(classes={KafkaConsumerTest.class})
。
仅加载消费者类时,监听器已停止触发。我有什么遗漏的吗?
这是 KafkaTestConsumer 类
@Service
public class KafkaTestConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTestConsumer.class);
private CountDownLatch latch = new CountDownLatch(1);
private String payload;
@KafkaListener(topics = {"topic"})
public void receive(ConsumerRecord<?, ?> consumerRecord) {
payload = consumerRecord.toString();
latch.countDown();
}
public CountDownLatch getLatch() {
return latch;
}
public void resetLatch() {
latch = new CountDownLatch(1);
}
public String getPayload() {
return payload;
}
}
很高兴看到您的
KafkaConsumerTest
是什么,但也许您只是用普通的 @Configuration
覆盖整个自动配置。
如果要自定义主要配置,可以使用嵌套的
类。与使用嵌套@TestConfiguration
类代替应用程序的主要配置不同,除了应用程序的主要配置之外,还使用嵌套@Configuration
类。@TestConfiguration
在我的例子中,原因是
spring.main.lazy-initialization
设置为 true
,这阻止了 KafkaListener 启动。