生产者#initTransactions不适用于KafkaContainer

问题描述 投票:0回答:2

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

java apache-kafka kafka-producer-api testcontainers
2个回答
1
投票

尝试使用Kafka for JUnit而不是Kafka testcontainers。我对事务有同样的问题,并以这种方式使它们活着。

我使用的Maven依赖:

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

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>
© www.soinside.com 2019 - 2024. All rights reserved.