栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带Spring Boot的简单嵌入式Kafka测试示例

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带Spring Boot的简单嵌入式Kafka测试示例

嵌入式Kafka测试适用于以下配置,

测试课注释

@EnableKafka@SpringBootTest(classes = {KafkaController.class}) // Specify @KafkaListener class if its not the same class, or not loaded with test config@EmbeddedKafka(    partitions = 1,     controlledShutdown = false,    brokerProperties = {        "listeners=PLAINTEXT://localhost:3333",         "port=3333"})public class KafkaConsumerTest {    @Autowired    KafkaEmbedded kafkaEmbeded;    @Autowired    KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

注释之前的设置方法

@Beforepublic void setUp() throws Exception {  for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) {    ContainerTestUtils.waitForAssignment(messageListenerContainer,     kafkaEmbeded.getPartitionsPerTopic());  }}

注意:我不是

@ClassRule
用来创建嵌入式Kafka而是自动装配
@Autowired embeddedKafka

@Testpublic void testReceive() throws Exception {     kafkaTemplate.send(topic, data);}

希望这可以帮助!

编辑:测试配置类标记为

@TestConfiguration

@TestConfigurationpublic class TestConfig {@Beanpublic ProducerFactory<String, String> producerFactory() {    return new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(kafkaEmbedded));}@Beanpublic KafkaTemplate<String, String> kafkaTemplate() {    KafkaTemplate<String, String> kafkaTemplate = new KafkaTemplate<>(producerFactory());    kafkaTemplate.setDefaultTopic(topic);    return kafkaTemplate;}

现在

@Test
方法将自动连接KafkaTemplate并用于发送消息

kafkaTemplate.send(topic, data);

用上面的行更新了答案代码块



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402948.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号