This repository was archived by the owner on Jun 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconsume.go
69 lines (56 loc) · 1.6 KB
/
consume.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 main
import (
"fmt"
"strings"
"github.com/Shopify/sarama"
log "github.com/Sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/bsm/sarama-cluster.v2"
)
// Consume consumes messages from Kafka
func Consume(cmd *cobra.Command, args []string) {
var config = sarama.NewConfig()
config.Net.TLS.Enable = true
config.Net.SASL.Enable = true
config.Net.SASL.User = Username
config.Net.SASL.Password = Password
config.Version = sarama.V0_10_0_1
config.ClientID = Username
if ConsumerGroup == "" {
ConsumerGroup = Username + ".go"
}
clusterConfig := cluster.NewConfig()
clusterConfig.Config = *config
clusterConfig.Consumer.Return.Errors = true
clusterConfig.Group.Return.Notifications = true
var err error
Consumer, err = cluster.NewConsumer(strings.Split(BrokerAddrs, ","), ConsumerGroup, []string{Topic}, clusterConfig)
HandleError(err)
// Consume errors
go func() {
for err := range Consumer.Errors() {
log.WithError(err).Error("Error during consumption")
}
}()
// Consume notifications
go func() {
for note := range Consumer.Notifications() {
log.WithField("note", note).Debug("Rebalanced consumer")
}
}()
fmt.Println("Ready to consume messages...")
// Consume messages
for msg := range Consumer.Messages() {
log.WithFields(log.Fields{
"consumerGroup": ConsumerGroup,
"topic": Topic,
"timestamp": msg.Timestamp,
"key": string(msg.Key),
"value": string(msg.Value),
"partition": msg.Partition,
"offset": msg.Offset,
}).Debug("Consume message")
Consumer.MarkOffset(msg, "")
fmt.Println(string(msg.Value))
}
}