Skip to content

Commit 2dcbc49

Browse files
committed
GH-1727: Close Producer if initTransactions Fails
Resolves #1727
1 parent 5e1cb82 commit 2dcbc49

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2020 the original author or authors.
2+
* Copyright 2016-2021 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -57,6 +57,7 @@
5757
import org.springframework.context.ApplicationListener;
5858
import org.springframework.context.event.ContextStoppedEvent;
5959
import org.springframework.core.log.LogAccessor;
60+
import org.springframework.kafka.KafkaException;
6061
import org.springframework.kafka.support.TransactionSupport;
6162
import org.springframework.lang.Nullable;
6263
import org.springframework.util.Assert;
@@ -519,7 +520,20 @@ private CloseSafeProducer<K, V> doCreateTxProducer(String prefix, String suffix,
519520
this.clientIdPrefix + "-" + this.clientIdCounter.incrementAndGet());
520521
}
521522
newProducer = createRawProducer(newProducerConfigs);
522-
newProducer.initTransactions();
523+
try {
524+
newProducer.initTransactions();
525+
}
526+
catch (RuntimeException ex) {
527+
try {
528+
newProducer.close(this.physicalCloseTimeout);
529+
}
530+
catch (RuntimeException ex2) {
531+
KafkaException newEx = new KafkaException("initTransactions() failed and then close() failed", ex);
532+
newEx.addSuppressed(ex2);
533+
throw newEx; // NOSONAR - lost stack trace
534+
}
535+
throw new KafkaException("initTransactions() failed", ex);
536+
}
523537
return new CloseSafeProducer<>(newProducer, getCache(prefix), remover,
524538
(String) newProducerConfigs.get(ProducerConfig.TRANSACTIONAL_ID_CONFIG), this.physicalCloseTimeout,
525539
this.epoch);

0 commit comments

Comments
 (0)