-
Notifications
You must be signed in to change notification settings - Fork 3
/
kafka.go
61 lines (50 loc) · 1.54 KB
/
kafka.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
package data_store
import (
"sync"
"github.com/Shopify/sarama"
log "github.com/shyyawn/go-to/x/logging"
"github.com/shyyawn/go-to/x/source"
"github.com/spf13/viper"
)
type Kafka struct {
config *sarama.Config
lock sync.RWMutex
producer sarama.AsyncProducer
Hosts []string `mapstructure:"hosts"`
Topic string `mapstructure:"topic"`
MaxMessageBytes int `mapstructure:"max_message_bytes"`
}
func (ds *Kafka) LoadFromConfig(key string, config *viper.Viper) error {
return source.LoadFromConfig(key, config, ds)
}
func (ds *Kafka) Producer() sarama.AsyncProducer {
if ds.producer != nil {
return ds.producer
}
defer ds.lock.Unlock()
ds.lock.Lock()
log.Info("Going to create the Kafka ASync Producer")
ds.config = sarama.NewConfig()
ds.config.Producer.RequiredAcks = sarama.WaitForAll
ds.config.Producer.Retry.Max = 10
ds.config.Producer.Return.Successes = false
if ds.MaxMessageBytes == 0 {
ds.MaxMessageBytes = 1000000
}
ds.config.Producer.MaxMessageBytes = ds.MaxMessageBytes
var err error
ds.producer, err = sarama.NewAsyncProducer(ds.Hosts, ds.config)
if err != nil {
log.Fatal("Failed to start Sarama producer:", err)
ds.producer = nil
}
// We will just log to STDOUT if we're not able to produce messages.
// Note: messages will only be returned here after all retry attempts are exhausted.
go func() {
for err := range ds.producer.Errors() {
log.Error("Failed to write access log entry, resetting producer:", err)
ds.producer = nil
}
}()
return ds.producer
}