我尝试通过事务向Kafka发送消息。因此,我使用以下代码:
try (Producer<Void, String> producer = createProducer(kafkaContainerBootstrapServers)) {
producer.initTransactions();
producer.beginTransaction();
Arrays.stream(messages).forEach(
message -> producer.send(new ProducerRecord<>(KAFKA_INPUT_TOPIC, message)));
producer.commitTransaction();
}..。
private static Producer<Void, String> createProducer(String kafkaContainerBootstrapServers) {
return new KafkaProducer<>(
ImmutableMap.of(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaContainerBootstrapServers,
ProducerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString(),
ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true,
ProducerConfig.TRANSACTIONAL_ID_CONFIG, UUID.randomUUID().toString()
),
new VoidSerializer(),
new StringSerializer());
}如果我使用本地的Kafka,它工作得很好。
但是如果我使用Kafka TestContainers,它在producer.initTransactions()上就会冻结
private static final String KAFKA_VERSION = "4.1.1";
@Rule
public KafkaContainer kafka = new KafkaContainer(KAFKA_VERSION)
.withEmbeddedZookeeper();如何配置KafkaContainer以处理事务?
发布于 2019-03-25 17:24:54
尝试使用Kafka for JUnit而不是Kafka测试容器。我在处理事务时遇到了同样的问题,并以这种方式使它们生效。
我使用的Maven依赖项:
<dependency>
<groupId>net.mguenther.kafka</groupId>
<artifactId>kafka-junit</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>发布于 2019-03-27 00:44:39
正如@AntonLitvinenko建议的那样,我在使用Kafka for JUnit时遇到了一个异常。我的问题是here。
我添加了这个依赖来修复它(参见issue):
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<version>2.12.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>另外,我对kafka-junit和kafka_2.11使用了2.0.1版本:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>${kafkaVersion}</version>
<scope>test</scope>
</dependency>https://stackoverflow.com/questions/55260840
复制相似问题