-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.go
68 lines (55 loc) · 1.65 KB
/
producer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package kp
import (
"context"
"github.com/Shopify/sarama"
"go.opentelemetry.io/contrib/instrumentation/github.com/Shopify/sarama/otelsarama"
"go.opentelemetry.io/otel"
)
var kpprodcer *Producer
type KPProducer interface {
GetProducer(kafkaConfig KafkaConfig) *Producer
ProduceMessage(ctx context.Context, topic string, key string, message string) error
}
type Producer struct {
producer sarama.SyncProducer
}
func NewProducer(kafkaConfig KafkaConfig) KPProducer {
if kpprodcer == nil {
saramaConfig := sarama.NewConfig()
saramaConfig.Producer.Partitioner = sarama.NewRandomPartitioner
saramaConfig.Producer.RequiredAcks = sarama.WaitForAll
saramaConfig.Producer.Return.Successes = true
producer, err := sarama.NewSyncProducer(kafkaConfig.KafkaBootstrapServers, saramaConfig)
if err != nil {
panic(err)
}
producer = otelsarama.WrapSyncProducer(saramaConfig, producer)
return &Producer{
producer: producer,
}
}
return kpprodcer
}
func (p *Producer) ProduceMessage(ctx context.Context, topic string, key string, message string) error {
messageToProduce := &sarama.ProducerMessage{
Topic: topic,
Key: sarama.StringEncoder(key),
Value: sarama.StringEncoder(message),
}
otel.GetTextMapPropagator().Inject(ctx, otelsarama.NewProducerMessageCarrier(messageToProduce))
_, _, err := p.producer.SendMessage(messageToProduce)
if err != nil {
return err
}
return nil
}
func (p *Producer) GetProducer(kafkaConfig KafkaConfig) *Producer {
return p
}
func GetProducer(kafkaConfig KafkaConfig) *Producer {
if kpprodcer == nil {
producer := NewProducer(kafkaConfig)
kpprodcer = producer.GetProducer(kafkaConfig)
}
return kpprodcer
}