测试应用
spring-kafka-test jar 包含一些实用工具,可帮助你测试应用程序。
当使用 Spring Boot 时,请改用 spring-boot-starter-kafka-test 依赖:
- Maven
- Gradle
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-kafka-test</artifactId>
<scope>test</scope>
</dependency>
testImplementation 'org.springframework.boot:spring-boot-starter-kafka-test'
内嵌 Kafka Broker
由于 Kafka 4.0 已完全过渡到 KRaft 模式,现在只有 EmbeddedKafkaKraftBroker 实现可用:
EmbeddedKafkaKraftBroker— 在组合控制器和 broker 模式下使用Kraft。
以下各节讨论了配置 broker 的几种技术。
KafkaTestUtils
org.springframework.kafka.test.utils.KafkaTestUtils 提供了许多静态辅助方法,用于消费记录、检索各种记录偏移量等。完整详情请参阅其 Javadocs。
JUnit
org.springframework.kafka.test.utils.KafkaTestUtils 提供了一些静态方法来设置生产者和消费者属性。下面的清单展示了这些方法签名:
/**
* Set up test properties for an {@code <Integer, String>} consumer.
* @param group the group id.
* @param autoCommit the auto commit.
* @param embeddedKafka a {@link EmbeddedKafkaBroker} instance.
* @return the properties.
*/
public static Map<String, Object> consumerProps(String group, String autoCommit,
EmbeddedKafkaBroker embeddedKafka) { ... }
/**
* Set up test properties for an {@code <Integer, String>} producer.
* @param embeddedKafka a {@link EmbeddedKafkaBroker} instance.
* @return the properties.
*/
public static Map<String, Object> producerProps(EmbeddedKafkaBroker embeddedKafka) { ... }
从 2.5 版本开始,consumerProps 方法将 ConsumerConfig.AUTO_OFFSET_RESET_CONFIG 设为 earliest。这是因为在大多数情况下,你希望消费者消费测试用例中发送的任何消息。ConsumerConfig 的默认值是 latest,这意味着在消费者启动之前测试已经发送的消息将不会收到那些记录。要恢复之前的行为,请在调用该方法后将属性设为 latest。
使用内嵌 broker 时,通常最佳实践是每个测试使用不同的主题,以防止交叉干扰。如果由于某些原因无法做到,请注意 consumeFromEmbeddedTopics 方法的默认行为是在分配后将已分配分区 seek 到起始位置。由于它无法访问消费者属性,你必须使用接受 seekToEnd 布尔参数的重载方法,以 seek 到末尾而非起始。
Spring for Apache Kafka 不再支持 JUnit 4。建议迁移到 JUnit Jupiter。
EmbeddedKafkaBroker 类有一个工具方法,让你可以消费它创建的所有主题。下面的示例展示了如何使用它:
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testT", "false", embeddedKafka);
DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
Consumer<Integer, String> consumer = cf.createConsumer();
embeddedKafka.consumeFromAllEmbeddedTopics(consumer);
KafkaTestUtils 有一些工具方法从消费者获取结果。下面的清单展示了这些方法签名:
/**
* Poll the consumer, expecting a single record for the specified topic.
* @param consumer the consumer.
* @param topic the topic.
* @return the record.
* @throws org.junit.ComparisonFailure if exactly one record is not received.
*/
public static <K, V> ConsumerRecord<K, V> getSingleRecord(Consumer<K, V> consumer, String topic) { ... }
/**
* Poll the consumer for records.
* @param consumer the consumer.
* @return the records.
*/
public static <K, V> ConsumerRecords<K, V> getRecords(Consumer<K, V> consumer) { ... }
下面的示例展示了如何使用 KafkaTestUtils:
...
template.sendDefault(0, 2, "bar");
ConsumerRecord<Integer, String> received = KafkaTestUtils.getSingleRecord(consumer, "topic");
...
当内嵌 Kafka broker 由 EmbeddedKafkaBroker 启动时,一个名为 spring.embedded.kafka.brokers 的系统属性会被设为 Kafka broker 的地址。为该属性提供了便捷常量(EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS)。
Kafka broker 的地址可以暴露给任意便捷属性,而非默认的 spring.embedded.kafka.brokers 系统属性。为此,可以在启动内嵌 Kafka 之前设置一个 spring.embedded.kafka.brokers.property(EmbeddedKafkaBroker.BROKER_LIST_PROPERTY)系统属性。例如,使用 Spring Boot 时,分别期望设置一个 spring.kafka.bootstrap-servers 配置属性来自动配置 Kafka 客户端。因此,在随机端口上使用内嵌 Kafka 运行测试之前,我们可以将 spring.embedded.kafka.brokers.property=spring.kafka.bootstrap-servers 设为系统属性——EmbeddedKafkaBroker 会用它来暴露其 broker 地址。这现在是该属性的默认值(从 3.0.10 版本开始)。
通过 EmbeddedKafkaBroker.brokerProperties(Map<String, String>),你可以为 Kafka 服务器提供额外属性。关于可用 broker 属性的更多信息请参阅 Kafka Config。
配置主题
下面的示例配置创建了名为 cat 和 hat 的两个主题(各五个分区)、名为 thing1 的主题(10 个分区)以及名为 thing2 的主题(15 个分区):
@SpringJUnitConfig
@EmbeddedKafka(
partitions = 5,
topics = {"cat", "hat"}
)
public class MyTests {
@Autowired
private EmbeddedKafkaBroker broker;
@Test
public void test() {
broker.addTopics(new NewTopic("thing1", 10, (short) 1), new NewTopic("thing2", 15, (short) 1));
...
}
}
默认情况下,当出现问题时(例如添加一个已存在的主题),addTopics 会抛出异常。2.6 版本新增了该方法的一个版本,返回一个 Map<String, Exception>;键是主题名,值在成功时为 null,失败时为一个 Exception。
多个测试类使用相同的 broker
你可以对多个测试类使用同一个 broker,类似如下方式:
public final class EmbeddedKafkaHolder {
private static EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaZKBroker(1, false)
.brokerListProperty("spring.kafka.bootstrap-servers");
private static volatile boolean started;
public static EmbeddedKafkaBroker getEmbeddedKafka() {
if (!started) {
synchronized (EmbeddedKafkaBroker.class) {
try {
embeddedKafka.afterPropertiesSet();
}
catch (Exception e) {
throw new KafkaException("Embedded broker failed to start", e);
}
started = true;
}
}
return embeddedKafka;
}
}
这假设是 Spring Boot 环境,内嵌 broker 会替换 bootstrap servers 属性。
然后,在每个测试类中,你可以使用类似如下方式:
static {
EmbeddedKafkaHolder.getEmbeddedKafka().addTopics("topic1", "topic2");
}
private static final EmbeddedKafkaBroker broker = EmbeddedKafkaHolder.getEmbeddedKafka();
如果你没有使用 Spring Boot,可以通过 broker.getBrokersAsString() 获取 bootstrap servers。
前面的示例没有提供在所有测试完成后关闭 broker 的机制。如果你在 Gradle 守护进程中运行测试,这可能是个问题。在这种情况下你不应使用这种技术,或者应使用某种方式在测试完成时对 EmbeddedKafkaBroker 调用 destroy()。
从 3.0 版本开始,框架为 JUnit Platform 暴露了一个 GlobalEmbeddedKafkaTestExecutionListener;它默认是禁用的。这需要 JUnit Platform 1.8 或更高版本。该监听器的目的是为整个测试计划启动一个全局 EmbeddedKafkaBroker,并在计划结束时停止它。要启用该监听器(从而为项目中所有测试提供单个全局内嵌 Kafka 集群),必须通过系统属性或 JUnit Platform 配置将 spring.kafka.global.embedded.enabled 属性设为 true。此外,还可以提供以下属性:
spring.kafka.embedded.count— 要管理的 Kafka broker 数量;spring.kafka.embedded.ports— 每个 Kafka broker 启动所用的端口(逗号分隔值),如果偏好随机端口则为0;值的数量必须等于上面提到的count;spring.kafka.embedded.topics— 在启动的 Kafka 集群中创建的主题(逗号分隔值);spring.kafka.embedded.partitions— 为所创建主题配置的分区数;spring.kafka.embedded.broker.properties.location— 额外 Kafka broker 配置属性的文件位置;该属性的值必须遵循 Spring 资源抽象模式。
本质上这些属性模拟了 @EmbeddedKafka 的一些属性。
关于配置属性以及如何提供它们的更多信息,请参阅 JUnit Jupiter 用户指南。例如,可以将一个 spring.embedded.kafka.brokers.property=my.bootstrap-servers 条目添加到测试类路径中的 junit-platform.properties 文件。从 3.0.10 版本开始,对于使用 Spring Boot 应用的测试,broker 会自动将其默认设为 spring.kafka.bootstrap-servers。
建议不要在单个测试套件中组合使用全局内嵌 Kafka 和按测试类的内嵌 Kafka。两者共享相同的系统属性,因此很可能导致意外行为。
spring-kafka-test 对 junit-jupiter-api 和 junit-platform-launcher(后者用于支持全局内嵌 broker)具有传递依赖。如果你希望使用内嵌 broker 但未在使用 JUnit,你可能希望排除这些依赖。
@EmbeddedKafka 注解
我们通常建议你使用单个 broker 实例,以避免在测试之间启动和停止 broker(并且每个测试使用不同的主题)。从 2.0 版本开始,如果你使用 Spring 的测试应用上下文缓存,也可以声明一个 EmbeddedKafkaBroker bean,这样单个 broker 可以跨多个测试类使用。为方便起见,我们提供了一个测试类级别的注解 @EmbeddedKafka 来注册 EmbeddedKafkaBroker bean。下面的示例展示了如何使用它:
@SpringJUnitConfig
@DirtiesContext
@EmbeddedKafka(partitions = 1,
topics = {
KafkaStreamsTests.STREAMING_TOPIC1,
KafkaStreamsTests.STREAMING_TOPIC2 })
public class KafkaStreamsTests {
@Autowired
private EmbeddedKafkaBroker embeddedKafka;
@Test
void someTest() {
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testGroup", "true", this.embeddedKafka);
consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
Consumer<Integer, String> consumer = cf.createConsumer();
this.embeddedKafka.consumeFromAnEmbeddedTopic(consumer, KafkaStreamsTests.STREAMING_TOPIC2);
ConsumerRecords<Integer, String> replies = KafkaTestUtils.getRecords(consumer);
assertThat(replies.count()).isGreaterThanOrEqualTo(1);
}
@Configuration
@EnableKafkaStreams
public static class TestKafkaStreamsConfiguration {
@Value("${" + EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS + "}")
private String brokerAddresses;
@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "testStreams");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddresses);
return new KafkaStreamsConfiguration(props);
}
}
}
从 2.2.4 版本开始,你还可以使用 @EmbeddedKafka 注解来指定 Kafka 端口属性。
从 4.0 版本开始,由于 Kafka 4.0 仅使用 KRaft,所有与 ZooKeeper 相关的属性已从 @EmbeddedKafka 注解中移除。
下面的示例设置了 @EmbeddedKafka 的 topics、brokerProperties 和 brokerPropertiesLocation 属性,支持属性占位符解析:
@TestPropertySource(locations = "classpath:/test.properties")
@EmbeddedKafka(topics = { "any-topic", "${kafka.topics.another-topic}" },
brokerProperties = { "log.dir=${kafka.broker.logs-dir}",
"listeners=PLAINTEXT://localhost:${kafka.broker.port}",
"auto.create.topics.enable=${kafka.broker.topics-enable:true}" },
brokerPropertiesLocation = "classpath:/broker.properties")
在前面的示例中,属性占位符 ${kafka.topics.another-topic}、${kafka.broker.logs-dir} 和 ${kafka.broker.port} 从 Spring Environment 解析。此外,broker 属性从 brokerPropertiesLocation 指定的 broker.properties 类路径资源加载。属性占位符会针对 brokerPropertiesLocation URL 以及资源中找到的任何属性占位符进行解析。由 brokerProperties 定义的属性会覆盖在 brokerPropertiesLocation 中找到的属性。
你可以将 @EmbeddedKafka 注解与 JUnit Jupiter 一起使用。
@EmbeddedKafka 注解与 JUnit Jupiter 配合
从 2.3 版本开始,有两种方式将 @EmbeddedKafka 注解与 JUnit Jupiter 一起使用。当与 @SpringJunitConfig 注解一起使用时,内嵌 broker 会被添加到测试应用上下文。你可以在类或方法级别将 broker 自动装配到测试中,以获取 broker 地址列表。
当不使用 spring 测试上下文时,EmbdeddedKafkaCondition 会创建一个 broker;该条件包含一个参数解析器,让你可以在测试方法中访问 broker。
@EmbeddedKafka
public class EmbeddedKafkaConditionTests {
@Test
public void test(EmbeddedKafkaBroker broker) {
String brokerList = broker.getBrokersAsString();
...
}
}
将创建一个独立 broker(在 Spring 的 TestContext 之外),除非标注了 @EmbeddedKafka 的类同时还标注了(或被元标注了)ExtendWith(SpringExtension.class)。@SpringJunitConfig 和 @SpringBootTest 是如此元标注的,当这两个注解之一也存在时将使用基于上下文的 broker。
当有 Spring 测试应用上下文可用时,主题和 broker 属性可以包含属性占位符,只要该属性在某处定义就会被解析。如果没有 Spring 上下文可用,这些占位符将不会被解析。
@SpringBootTest 注解中的内嵌 broker
Spring Initializr 现在会在项目配置中自动以 test 作用域添加 spring-kafka-test 依赖。
如果你的应用在 spring-cloud-stream 中使用 Kafka binder,并且你希望在内嵌 broker 上进行测试,你必须移除 spring-cloud-stream-test-support 依赖,因为它会用测试 binder 替换真实 binder 用于测试用例。如果你希望某些测试使用测试 binder、某些使用内嵌 broker,那么使用真实 binder 的测试需要在测试类中排除 binder 自动配置来禁用测试 binder。下面的示例展示了如何做到这一点:
@SpringJUnitConfig
@SpringBootTest(properties = "spring.autoconfigure.exclude="
+ "org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration")
public class MyApplicationTests {
...
}
:::
在 Spring Boot 应用测试中使用内嵌 broker 有几种方式。
它们包括:
@EmbeddedKafka 与 @SpringJunitConfig 配合
当将 @EmbeddedKafka 与 @SpringJUnitConfig 一起使用时,建议在测试类上使用 @DirtiesContext。这是为了防止在测试套件中运行多个测试后、JVM 关闭期间可能发生的竞态条件。例如,不使用 @DirtiesContext 时,EmbeddedKafkaBroker 可能会过早关闭,而应用上下文仍需要它的资源。由于每次 EmbeddedKafka 测试运行都会创建自己的临时目录,当这种竞态条件发生时,会产生错误日志消息,表明它试图删除或清理的文件已不可用。添加 @DirtiesContext 会确保每个测试后应用上下文被清理且不被缓存,使其不易受到这类潜在资源竞态条件的影响。
@EmbeddedKafka 注解或 EmbeddedKafkaBroker Bean
下面的示例展示了如何使用 @EmbeddedKafka 注解创建一个内嵌 broker:
@SpringJUnitConfig
@EmbeddedKafka(topics = "someTopic",
bootstrapServersProperty = "spring.kafka.bootstrap-servers") // this is now the default
public class MyApplicationTests {
@Autowired
private KafkaTemplate<String, String> template;
@Test
void test() {
...
}
}
从 3.0.10 版本开始,bootstrapServersProperty 默认会自动设为 spring.kafka.bootstrap-servers。
Hamcrest 匹配器
org.springframework.kafka.test.hamcrest.KafkaMatchers 提供以下匹配器:
/**
* @param key the key
* @param <K> the type.
* @return a Matcher that matches the key in a consumer record.
*/
public static <K> Matcher<ConsumerRecord<K, ?>> hasKey(K key) { ... }
/**
* @param value the value.
* @param <V> the type.
* @return a Matcher that matches the value in a consumer record.
*/
public static <V> Matcher<ConsumerRecord<?, V>> hasValue(V value) { ... }
/**
* @param partition the partition.
* @return a Matcher that matches the partition in a consumer record.
*/
public static Matcher<ConsumerRecord<?, ?>> hasPartition(int partition) { ... }
/**
* Matcher testing the timestamp of a {@link ConsumerRecord} assuming the topic has been set with
* {@link org.apache.kafka.common.record.TimestampType#CREATE_TIME CreateTime}.
*
* @param ts timestamp of the consumer record.
* @return a Matcher that matches the timestamp in a consumer record.
*/
public static Matcher<ConsumerRecord<?, ?>> hasTimestamp(long ts) {
return hasTimestamp(TimestampType.CREATE_TIME, ts);
}
/**
* Matcher testing the timestamp of a {@link ConsumerRecord}
* @param type timestamp type of the record
* @param ts timestamp of the consumer record.
* @return a Matcher that matches the timestamp in a consumer record.
*/
public static Matcher<ConsumerRecord<?, ?>> hasTimestamp(TimestampType type, long ts) {
return new ConsumerRecordTimestampMatcher(type, ts);
}
AssertJ 条件
你可以使用以下 AssertJ 条件:
/**
* @param key the key
* @param <K> the type.
* @return a Condition that matches the key in a consumer record.
*/
public static <K> Condition<ConsumerRecord<K, ?>> key(K key) { ... }
/**
* @param value the value.
* @param <V> the type.
* @return a Condition that matches the value in a consumer record.
*/
public static <V> Condition<ConsumerRecord<?, V>> value(V value) { ... }
/**
* @param key the key.
* @param value the value.
* @param <K> the key type.
* @param <V> the value type.
* @return a Condition that matches the key in a consumer record.
* @since 2.2.12
*/
public static <K, V> Condition<ConsumerRecord<K, V>> keyValue(K key, V value) { ... }
/**
* @param partition the partition.
* @return a Condition that matches the partition in a consumer record.
*/
public static Condition<ConsumerRecord<?, ?>> partition(int partition) { ... }
/**
* @param value the timestamp.
* @return a Condition that matches the timestamp value in a consumer record.
*/
public static Condition<ConsumerRecord<?, ?>> timestamp(long value) {
return new ConsumerRecordTimestampCondition(TimestampType.CREATE_TIME, value);
}
/**
* @param type the type of timestamp
* @param value the timestamp.
* @return a Condition that matches the timestamp value in a consumer record.
*/
public static Condition<ConsumerRecord<?, ?>> timestamp(TimestampType type, long value) {
return new ConsumerRecordTimestampCondition(type, value);
}
示例
下面的示例汇集了本章涵盖的大部分主题:
@EmbeddedKafka(topics = KafkaTemplateTests.TEMPLATE_TOPIC)
public class KafkaTemplateTests {
public static final String TEMPLATE_TOPIC = "templateTopic";
public static EmbeddedKafkaBroker embeddedKafka;
@BeforeAll
public static void setUp() {
embeddedKafka = EmbeddedKafkaCondition.getBroker();
}
@Test
public void testTemplate() throws Exception {
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testT", "false",
embeddedKafka);
DefaultKafkaConsumerFactory<Integer, String> cf =
new DefaultKafkaConsumerFactory<>(consumerProps);
ContainerProperties containerProperties = new ContainerProperties(TEMPLATE_TOPIC);
KafkaMessageListenerContainer<Integer, String> container =
new KafkaMessageListenerContainer<>(cf, containerProperties);
final BlockingQueue<ConsumerRecord<Integer, String>> records = new LinkedBlockingQueue<>();
container.setupMessageListener(new MessageListener<Integer, String>() {
@Override
public void onMessage(ConsumerRecord<Integer, String> record) {
System.out.println(record);
records.add(record);
}
});
container.setBeanName("templateTests");
container.start();
ContainerTestUtils.waitForAssignment(container,
embeddedKafka.getPartitionsPerTopic());
Map<String, Object> producerProps =
KafkaTestUtils.producerProps(embeddedKafka);
ProducerFactory<Integer, String> pf =
new DefaultKafkaProducerFactory<>(producerProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
template.setDefaultTopic(TEMPLATE_TOPIC);
template.sendDefault("foo");
assertThat(records.poll(10, TimeUnit.SECONDS), hasValue("foo"));
template.sendDefault(0, 2, "bar");
ConsumerRecord<Integer, String> received = records.poll(10, TimeUnit.SECONDS);
assertThat(received, hasKey(2));
assertThat(received, hasPartition(0));
assertThat(received, hasValue("bar"));
template.send(TEMPLATE_TOPIC, 0, 2, "baz");
received = records.poll(10, TimeUnit.SECONDS);
assertThat(received, hasKey(2));
assertThat(received, hasPartition(0));
assertThat(received, hasValue("baz"));
}
}
前面的示例使用了 Hamcrest 匹配器。使用 AssertJ 时,最后部分如下所示:
assertThat(records.poll(10, TimeUnit.SECONDS)).has(value("foo"));
template.sendDefault(0, 2, "bar");
ConsumerRecord<Integer, String> received = records.poll(10, TimeUnit.SECONDS);
// using individual assertions
assertThat(received).has(key(2));
assertThat(received).has(value("bar"));
assertThat(received).has(partition(0));
template.send(TEMPLATE_TOPIC, 0, 2, "baz");
received = records.poll(10, TimeUnit.SECONDS);
// using allOf()
assertThat(received).has(allOf(keyValue(2, "baz"), partition(0)));
Mock 消费者和生产者
kafka-clients 库提供了 MockConsumer 和 MockProducer 类用于测试目的。
如果你希望在某些测试中将这些类分别与监听器容器或 KafkaTemplate 一起使用,从 3.0.7 版本开始,框架现在提供了 MockConsumerFactory 和 MockProducerFactory 实现。
这些工厂可以在监听器容器和模板中使用,替代需要运行(或内嵌)broker 的默认工厂。
下面是一个返回单个消费者的简单实现示例:
@Bean
ConsumerFactory<String, String> consumerFactory() {
MockConsumer<String, String> consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
TopicPartition topicPartition0 = new TopicPartition("topic", 0);
List<TopicPartition> topicPartitions = Collections.singletonList(topicPartition0);
Map<TopicPartition, Long> beginningOffsets = topicPartitions.stream().collect(Collectors
.toMap(Function.identity(), tp -> 0L));
consumer.updateBeginningOffsets(beginningOffsets);
consumer.schedulePollTask(() -> {
consumer.addRecord(
new ConsumerRecord<>("topic", 0, 0L, 0L, TimestampType.NO_TIMESTAMP_TYPE, 0, 0, null, "test1",
new RecordHeaders(), Optional.empty()));
consumer.addRecord(
new ConsumerRecord<>("topic", 0, 1L, 0L, TimestampType.NO_TIMESTAMP_TYPE, 0, 0, null, "test2",
new RecordHeaders(), Optional.empty()));
});
return new MockConsumerFactory(() -> consumer);
}
如果你希望以并发方式测试,工厂构造器中的 Supplier lambda 需要每次创建一个新实例。
对于 MockProducerFactory,有两个构造器;一个创建简单工厂,一个创建支持事务的工厂。
下面是示例:
@Bean
ProducerFactory<String, String> nonTransFactory() {
return new MockProducerFactory<>(() ->
new MockProducer<>(true, new StringSerializer(), new StringSerializer()));
}
@Bean
ProducerFactory<String, String> transFactory() {
MockProducer<String, String> mockProducer =
new MockProducer<>(true, new StringSerializer(), new StringSerializer());
mockProducer.initTransactions();
return new MockProducerFactory<String, String>((tx, id) -> mockProducer, "defaultTxId");
}
注意在第二种情况下,lambda 是一个 BiFunction<Boolean, String>,其中第一个参数为 true 表示调用者希望使用事务性生产者;可选的第二个参数包含事务 id。它可以是默认值(如构造器中提供的),或者如果如此配置,可以被 KafkaTransactionManager(或本地事务的 KafkaTemplate)覆盖。事务 id 被提供出来,以便你可以基于此值使用不同的 MockProducer。
如果你在多线程环境中使用生产者,BiFunction 应返回多个生产者(或许使用 ThreadLocal 绑定到线程)。
事务性 MockProducer 必须通过调用 initTransaction() 进行事务初始化。
使用 MockProducer 时,如果你不希望每次发送后关闭生产者,那么可以提供一个自定义 MockProducer 实现,覆盖 close 方法且不调用超类的 close 方法。这在测试时很方便,可以在同一生产者上验证多次发布而不关闭它。
下面是一个示例:
@Bean
MockProducer<String, String> mockProducer() {
return new MockProducer<>(false, new StringSerializer(), new StringSerializer()) {
@Override
public void close() {
}
};
}
@Bean
ProducerFactory<String, String> mockProducerFactory(MockProducer<String, String> mockProducer) {
return new MockProducerFactory<>(() -> mockProducer);
}