Skip to content

Commit c676c7b

Browse files
committed
retry producer creation upon error
1 parent ec846ff commit c676c7b

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

pulsar/producer_partition.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,49 @@ func newPartitionProducer(client *client, topic string, options *ProducerOptions
185185
} else {
186186
p.userProvidedProducerName = false
187187
}
188-
err := p.grabCnx()
188+
// retry to create producer when failed with maxRetry
189+
var maxRetry int
190+
if p.options.MaxReconnectToBroker == nil {
191+
maxRetry = -1
192+
} else {
193+
maxRetry = int(*p.options.MaxReconnectToBroker)
194+
}
195+
196+
var delayReconnectTime time.Duration
197+
defaultBackoff := internal.DefaultBackoff{}
198+
199+
var err error
200+
for maxRetry != 0 {
201+
if p.options.BackoffPolicy == nil {
202+
delayReconnectTime = defaultBackoff.Next()
203+
} else {
204+
delayReconnectTime = p.options.BackoffPolicy.Next()
205+
}
206+
207+
atomic.AddUint64(&p.epoch, 1)
208+
err = p.grabCnx()
209+
if err == nil {
210+
break
211+
}
212+
p.log.WithError(err).Error("Failed to create producer at newPartitionProducer")
213+
errMsg := err.Error()
214+
if strings.Contains(errMsg, errTopicNotFount) {
215+
// when topic is not found, do not attempt to reconnect
216+
p.log.Warn("Failed to create producer due to Topic Not Found")
217+
break
218+
}
219+
220+
if strings.Contains(errMsg, "TopicTerminatedError") {
221+
p.log.Info("Topic was terminated, failing pending messages, will not create producer")
222+
break
223+
}
224+
225+
if maxRetry > 0 {
226+
maxRetry--
227+
}
228+
logger.WithError(err).Error("Failed to create producer at newPartitionProducer retry to create producer", delayReconnectTime)
229+
time.Sleep(delayReconnectTime)
230+
}
189231
if err != nil {
190232
p.batchFlushTicker.Stop()
191233
logger.WithError(err).Error("Failed to create producer at newPartitionProducer")

0 commit comments

Comments
 (0)