-
Notifications
You must be signed in to change notification settings - Fork 3
/
producer.go
52 lines (41 loc) · 1.14 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
package kafka
import (
"github.com/IBM/sarama"
)
type Producer interface {
Produce(msg *sarama.ProducerMessage) error
}
// ProducerHandler is a function that handles the production of a message. It is exposed to allow for easy middleware building.
type ProducerHandler func(p *producer, msg *sarama.ProducerMessage) error
type producer struct {
handler ProducerHandler
producer sarama.SyncProducer
instrumenting *ProducerMetricsService
}
// NewProducer creates a new producer that uses the default sarama client.
func NewProducer(options ...ProducerOption) (Producer, error) {
client, err := getClient()
if err != nil {
return nil, err
}
p, err := sarama.NewSyncProducerFromClient(*client)
if err != nil {
return nil, err
}
producer := &producer{
producer: p,
handler: produce,
}
for _, option := range options {
option(producer)
}
return producer, nil
}
// Produce sends a message to the kafka cluster.
func (p *producer) Produce(msg *sarama.ProducerMessage) error {
return p.handler(p, msg)
}
func produce(p *producer, msg *sarama.ProducerMessage) error {
_, _, err := p.producer.SendMessage(msg)
return err
}