-
Notifications
You must be signed in to change notification settings - Fork 440
/
sync_writer.go
69 lines (56 loc) · 1.22 KB
/
sync_writer.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
package kafka
import (
"strconv"
"time"
"github.com/Shopify/sarama"
)
type SyncWriter struct {
brokers []string
topic string
partition int32
producer sarama.SyncProducer
config *Config
}
func NewSyncWriter(rootCaFile, address string, partitionId int) (*SyncWriter, error) {
c, err := NewConfig(rootCaFile)
if err != nil {
return nil, err
}
topic, brokers, err := parse(address)
if err != nil {
return nil, err
}
s := &SyncWriter{
brokers: brokers,
topic: topic,
partition: int32(partitionId),
config: c,
}
return s, nil
}
func (s *SyncWriter) Start() error {
producer, err := sarama.NewSyncProducer(s.brokers, s.config.Config)
if err != nil {
return err
}
s.producer = producer
return nil
}
func (s *SyncWriter) SimpleWrite(input []byte) error {
return s.send(input)
}
func (s *SyncWriter) send(input []byte) error {
// use timestamp as key
key := strconv.FormatInt(time.Now().UnixNano(), 16)
msg := &sarama.ProducerMessage{
Topic: s.topic,
Partition: s.partition,
Key: sarama.ByteEncoder(key),
Value: sarama.ByteEncoder(input),
}
_, _, err := s.producer.SendMessage(msg)
return err
}
func (s *SyncWriter) Close() error {
return s.producer.Close()
}