-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
49 lines (40 loc) · 953 Bytes
/
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
package easykafka
import (
"context"
"encoding/json"
"github.com/segmentio/kafka-go"
)
// Producer is a wrapper around BaseProducer
type Producer[T any] struct {
*BaseProducer
}
// InitProducer initializes a new Producer instance
func InitProducer[T any](
brokers []string,
opts ...BaseProducerOption,
) (producer *Producer[T], close func() error) {
baseProducer, closeBaseProducer := InitBaseProducer(brokers, opts...)
producer = &Producer[T]{
BaseProducer: baseProducer,
}
return producer, closeBaseProducer
}
// Produce sends messages to kafka
func (p *Producer[T]) Produce(ctx context.Context, topics []string, messages ...*T) error {
var kms []*kafka.Message
for _, m := range messages {
b, err := json.Marshal(m)
if err != nil {
return err
}
for _, topic := range topics {
kms = append(
kms,
&kafka.Message{
Value: b,
Topic: topic,
})
}
}
return p.BaseProducer.Produce(ctx, kms...)
}