Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix kafka producer init many times #26314

Merged
merged 1 commit into from
Aug 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions pkg/mq/msgstream/mqwrapper/kafka/kafka_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@ import (
"sync"

"github.com/confluentinc/confluent-kafka-go/kafka"
"go.uber.org/atomic"
"go.uber.org/zap"

"github.com/milvus-io/milvus/pkg/log"
"github.com/milvus-io/milvus/pkg/metrics"
"github.com/milvus-io/milvus/pkg/mq/msgstream/mqwrapper"
"github.com/milvus-io/milvus/pkg/util/conc"
"github.com/milvus-io/milvus/pkg/util/paramtable"
"github.com/milvus-io/milvus/pkg/util/timerecord"
)

var producer *kafka.Producer
var (
producer atomic.Pointer[kafka.Producer]
sf conc.Singleflight[*kafka.Producer]
)

var once sync.Once

Expand Down Expand Up @@ -85,15 +90,21 @@ func cloneKafkaConfig(config kafka.ConfigMap) *kafka.ConfigMap {
}

func (kc *kafkaClient) getKafkaProducer() (*kafka.Producer, error) {
config := kc.newProducerConfig()
producer, err := kafka.NewProducer(config)
if err != nil {
log.Error("create sync kafka producer failed", zap.Error(err))
return nil, err
if p := producer.Load(); p != nil {
return p, nil
}
once.Do(func() {
p, err, _ := sf.Do("kafka_producer", func() (*kafka.Producer, error) {
if p := producer.Load(); p != nil {
return p, nil
}
config := kc.newProducerConfig()
p, err := kafka.NewProducer(config)
if err != nil {
log.Error("create sync kafka producer failed", zap.Error(err))
return nil, err
}
go func() {
for e := range producer.Events() {
for e := range p.Events() {
switch ev := e.(type) {
case kafka.Error:
// Generic client instance-level errors, such as broker connection failures,
Expand All @@ -109,9 +120,13 @@ func (kc *kafkaClient) getKafkaProducer() (*kafka.Producer, error) {
}
}
}()
producer.Store(p)
return p, nil
})

return producer, nil
if err != nil {
return nil, err
}
return p, nil
}

func (kc *kafkaClient) newProducerConfig() *kafka.ConfigMap {
Expand Down