Producer#initTransactions不适用于KafkaContainer

时间:2019-03-20 12:30:16

标签: java apache-kafka kafka-producer-api testcontainers

我尝试通过事务向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以处理事务?

2 个答案:

答案 0 :(得分:1)

尝试使用Kafka for JUnit代替Kafka测试容器。我在交易时遇到了同样的问题,并以此方式使它们活着。

我使用的Maven依赖项:

<dependency>
    <groupId>net.mguenther.kafka</groupId>
    <artifactId>kafka-junit</artifactId>
    <version>2.1.0</version>
    <scope>test</scope>
</dependency>

答案 1 :(得分:0)

我按@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>

此外,我将2.0.1版本用于kafka-junit和kafka_2.11:

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>${kafkaVersion}</version>
    <scope>test</scope>
</dependency>