-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
53 lines (44 loc) · 965 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
50
51
52
53
package messaging
import (
"context"
"encoding/json"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"github.com/segmentio/kafka-go"
)
type KafkaWriter interface {
WriteMessages(context.Context, ...kafka.Message) error
Close() error
}
type Producer struct {
writer KafkaWriter
}
func NewProducer(broker string) *Producer {
producer := Producer{
writer: kafka.NewWriter(kafka.WriterConfig{
Brokers: []string{broker},
Topic: "topic-A",
Balancer: &kafka.LeastBytes{},
}),
}
return &producer
}
func (p *Producer) WriteMessage(mess Message) {
m, err := json.Marshal(mess)
if err != nil {
log.Errorf("failed to marshal json message: %s", err)
return
}
err = p.writer.WriteMessages(context.Background(),
kafka.Message{
Key: []byte(uuid.New().String()),
Value: m,
},
)
if err != nil {
log.Errorf("failed to write message %+v to kafka: %s", m, err)
}
}
func (p *Producer) close() {
p.writer.Close()
}