forked from chiguirez/kfk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
75 lines (61 loc) · 1.62 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
74
75
package kfk
import (
"encoding/json"
"reflect"
"github.com/Shopify/sarama"
)
// Producer
type KafkaProducer struct {
producer sarama.SyncProducer
}
// NewKafkaProducer
func NewKafkaProducer(kafkaBrokers []string) (*KafkaProducer, error) {
kafkaCfg := sarama.NewConfig()
kafkaCfg.Consumer.Return.Errors = true
kafkaCfg.Version = sarama.V1_0_0_0
kafkaCfg.Consumer.Offsets.Initial = sarama.OffsetOldest
kafkaCfg.Producer.Return.Successes = true
producer, err := sarama.NewSyncProducer(kafkaBrokers, kafkaCfg)
if err != nil {
return nil, err
}
return &KafkaProducer{producer}, nil
}
// Send a message to a topic to be scattered using the key
func (p *KafkaProducer) Send(topic string, key string, message interface{}) error {
bytes, err := p.encode(message)
if err != nil {
return err
}
producerMessage := &sarama.ProducerMessage{
Topic: topic,
Value: sarama.ByteEncoder(bytes),
Key: sarama.ByteEncoder([]byte(key)),
Headers: []sarama.RecordHeader{messageTypeHeader(message)},
}
_, _, err = p.producer.SendMessage(producerMessage)
return err
}
type Marshaler interface {
MarshalKFK() ([]byte, error)
}
func (p *KafkaProducer) encode(message interface{}) ([]byte, error) {
marshall, ok := message.(Marshaler)
if ok {
return marshall.MarshalKFK()
}
return json.Marshal(message)
}
func messageTypeHeader(message interface{}) sarama.RecordHeader {
return sarama.RecordHeader{
Key: []byte("@type"),
Value: []byte(messageType(message)),
}
}
func messageType(m interface{}) string {
rType := reflect.TypeOf(m)
if rType.Kind() == reflect.Ptr {
return rType.Elem().Name()
}
return rType.Name()
}