-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.go
73 lines (58 loc) · 1.43 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
69
70
71
72
73
package kafka
import (
"github.com/Shopify/sarama"
)
type ProducerOptions struct {
Topic string
Brokers []string
BufferSize int
}
type AsyncProducer interface {
Send(message *Message)
Errors() <-chan error
Close() error
}
func NewAsyncProducer(opts *ProducerOptions, config *sarama.Config) (AsyncProducer, error) {
return newAsyncProducer(opts, config)
}
type asyncProducer struct {
opts *ProducerOptions
producer sarama.AsyncProducer
buffer chan *sarama.ProducerMessage
errors chan error
}
func newAsyncProducer(opts *ProducerOptions, config *sarama.Config) (*asyncProducer, error) {
err := config.Validate()
if err != nil {
return nil, err
}
p, err := sarama.NewAsyncProducer(opts.Brokers, config)
if err != nil {
return nil, err
}
bufferSize := 4096
if opts.BufferSize > 0 {
bufferSize = opts.BufferSize
}
producer := &asyncProducer{
opts: opts,
buffer: make(chan *sarama.ProducerMessage, bufferSize),
producer: p,
}
go producer.loop()
return producer, nil
}
func (p *asyncProducer) Send(message *Message) {
p.producer.Input() <- &sarama.ProducerMessage{Topic: p.opts.Topic, Key: sarama.ByteEncoder(message.Key), Value: sarama.ByteEncoder(message.Value)}
}
func (p *asyncProducer) Errors() <-chan error {
return p.errors
}
func (p *asyncProducer) Close() error {
return p.producer.Close()
}
func (p *asyncProducer) loop() {
for err := range p.producer.Errors() {
p.errors <- err
}
}