From 52408e4aad6f4ba89f6ba949bc998a9cd2337ce9 Mon Sep 17 00:00:00 2001 From: Gary Russell Date: Wed, 3 Mar 2021 11:19:37 -0500 Subject: [PATCH] GH-1727: Close Producer if initTransactions Fails Resolves https://github.com/spring-projects/spring-kafka/issues/1727 --- .../core/DefaultKafkaProducerFactory.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java b/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java index 8c6c0fd0..4124a921 100644 --- a/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java +++ b/spring-kafka/src/main/java/org/springframework/kafka/core/DefaultKafkaProducerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2020 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,6 +57,7 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextStoppedEvent; import org.springframework.core.log.LogAccessor; +import org.springframework.kafka.KafkaException; import org.springframework.kafka.support.TransactionSupport; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -508,7 +509,20 @@ public class DefaultKafkaProducerFactory implements ProducerFactory, this.clientIdPrefix + "-" + this.clientIdCounter.incrementAndGet()); } newProducer = createRawProducer(newProducerConfigs); - newProducer.initTransactions(); + try { + newProducer.initTransactions(); + } + catch (RuntimeException ex) { + try { + newProducer.close(this.physicalCloseTimeout); + } + catch (RuntimeException ex2) { + KafkaException newEx = new KafkaException("initTransactions() failed and then close() failed", ex); + newEx.addSuppressed(ex2); + throw newEx; // NOSONAR - lost stack trace + } + throw new KafkaException("initTransactions() failed", ex); + } return new CloseSafeProducer<>(newProducer, getCache(prefix), remover, (String) newProducerConfigs.get(ProducerConfig.TRANSACTIONAL_ID_CONFIG), this.physicalCloseTimeout, this.epoch);