如何在test中模拟Kafka broker? EmbeddedKafka如何使用?

EmbeddedKafkaBroker

1. EmbeddedKafkaRule vs. EmbeddedKafkaBroker

EmbeddedKafkaRule: A TestRule wrapper around an EmbeddedKafkaBroker.
查看源码,发现他俩都是创建一些虚拟的broker给test使用的。

然后看到这样一段话,不过对我没有什么用:
TopicAlreadyExists exceptions:
Some suggestions:

  1. Since you are using JUnit5, don’t use the JUnit4 EmbeddedKafkaRule, use EmbeddedKafkaBrokerinstead; or simply add @EmbeddedKafkaand the broker will be added as a bean to the Spring application context and its life cycle managed by Spring (use @DirtiesContext to destroy); for non-Spring tests, the broker will be created (and destroyed) by the JUnit5 EmbeddedKafkaConditionand is available via EmbeddedKafkaCondition.getBroker().
  2. Don’t use explicit ports; let the broker use its default random port and use embeddedKafka.getBrokersAsString() for the bootstrap servers property.
  3. If you must manage the brokers yourself (in @BeforeAll), destroy() them in @AfterAll

1.1 EmbeddedKafkaRule

Spring-kafka-test provides an embedded Kafka broker. We can use a JUnit @ClassRule annotation to create this Kafka broker. This rule starts the Kafka and Zookeeper servers on a random port before the tests execute and shuts them down after the tests are complete. The embedded Kafka broker eliminates the need to have a real Kafka and Zookeeper instance running while running the test.

官方文档: A JUnit 4 @Rule wrapper for the EmbeddedKafkaBroker is provided to create an embedded Kafka and an embedded Zookeeper server. (See @EmbeddedKafka Annotation for information about using @EmbeddedKafka with JUnit 5).

Starting with version 2.0, if you use Spring’s test application context caching, you can also declare a EmbeddedKafkaBroker bean, so a single broker can be used across multiple test classes. For convenience, we provide a test class-level annotation called @EmbeddedKafka to register the EmbeddedKafkaBroker bean. The following example shows how to use it:

@RunWith(SpringRunner.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值