-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.go
56 lines (44 loc) · 1.12 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
package kafka
import (
"context"
"fmt"
"github.com/IBM/sarama"
"github.com/spf13/viper"
)
type KafkaProducer struct {
config Config
producer sarama.AsyncProducer
}
func NewKafkaProducer(vp *viper.Viper, field string) (producer *KafkaProducer, err error) {
var (
config *Config
scfg *sarama.Config
)
if config, scfg, err = NewConfigFromViper(vp, field); err != nil {
return nil, err
}
if config.Topic == "" || config.Key == "" {
return nil, fmt.Errorf("neither the topic nor the key is set")
}
producer = &KafkaProducer{config: *config}
producer.producer, err = sarama.NewAsyncProducer(producer.config.Addrs, scfg)
if err != nil {
return nil, err
}
return producer, nil
}
func (producer *KafkaProducer) SendMsg(ctx context.Context, bts []byte) (msg *sarama.ProducerMessage) {
msg = &sarama.ProducerMessage{
Topic: producer.config.Topic,
Key: sarama.StringEncoder(producer.config.Key),
Value: sarama.ByteEncoder(bts),
}
select {
case <-ctx.Done():
case producer.producer.Input() <- msg:
}
return msg
}
func (producer *KafkaProducer) Close() (err error) {
return producer.producer.Close()
}