/
consumer.go
189 lines (159 loc) · 3.95 KB
/
consumer.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package kafka
import (
"context"
"fmt"
"github.com/Shopify/sarama"
cluster "github.com/bsm/sarama-cluster"
"github.com/itea-tgl/itea-go/constant"
"github.com/itea-tgl/itea-go/ilog"
"github.com/itea-tgl/itea-go/ioc/iface"
"strings"
)
const (
KEY_KEY = "Key"
HANDLER_KEY = "Handler"
)
type KafkaConsumer struct {
Ctx context.Context
Ioc iface.IIoc
Name string
Brokers string
Topic string
Group string
Processor []interface{}
consumer *cluster.Consumer
handler map[string][]IHandler
debug bool
}
func (kc *KafkaConsumer) Execute() {
if d, ok := kc.Ctx.Value(constant.DEBUG).(bool); ok {
kc.debug = d
}
// init (custom) config, enable errors and notifications
config := cluster.NewConfig()
config.Group.Mode = cluster.ConsumerModePartitions
config.Consumer.Return.Errors = true
config.Group.Return.Notifications = true
// init consumer
if kc.Brokers == "" {
panic("kafka broker can not be empty")
}
brokers := strings.Split(kc.Brokers, ",")
if kc.Topic == "" {
panic("kafka topic can not be empty")
}
topics := []string{kc.Topic}
if kc.Group == "" {
kc.Group = fmt.Sprintf("%s%s%d", kc.Topic, "_group_", 1)
}
var err error
kc.consumer, err = cluster.NewConsumer(brokers, kc.Group, topics, config)
if err != nil {
panic(err)
}
// consume errors
go func() {
for err := range kc.consumer.Errors() {
ilog.Error("consumer error: ", err.Error())
}
}()
// consume notifications
go func() {
for ntf := range kc.consumer.Notifications() {
ilog.Info(fmt.Sprintf("consumer rebalanced: %+v", ntf))
}
}()
kc.initHandler()
ilog.Info(fmt.Sprintf("=== 【Kafka】Consumer [%s] start [Topic : %s, Group : %s] ===", kc.Name, kc.Topic, kc.Group))
kc.start()
}
func (kc *KafkaConsumer) initHandler() {
kc.handler = map[string][]IHandler{}
for _, v := range kc.Processor {
if i, ok := v.(string); ok {
kc.appendHandler("", i)
continue
}
if i, ok := v.(map[interface{}]interface{}); ok {
k := ""
if _, ok := i[KEY_KEY]; ok {
k = i[KEY_KEY].(string)
}
kc.appendHandler(k, i[HANDLER_KEY].(string))
}
}
}
func (kc *KafkaConsumer) appendHandler(k string, i string) {
h := kc.Ioc.InsByName(i)
if h == nil {
ilog.Error(fmt.Sprintf("consumer [%s] is nil, please check out if [%s] is registed", i, i))
return
}
if v, ok := h.(IHandler); ok {
if _, ok := kc.handler[k]; !ok {
kc.handler[k] = []IHandler{}
}
kc.handler[k] = append(kc.handler[k], v)
return
}
ilog.Error(fmt.Sprintf("consumer [%s] is not impliment of kafka.IHandler", i))
}
func (kc *KafkaConsumer) start () {
stop := make(chan bool, 1)
go kc.stop(stop)
// consume messages, watch signals
for {
select {
case part, ok := <-kc.consumer.Partitions():
if !ok {
return
}
// start a separate goroutine to consume messages
go func(pc cluster.PartitionConsumer) {
for msg := range pc.Messages() {
if kc.debug {
ilog.Info(fmt.Sprintf("【Kafka Receive】 partition: %d, key: %s, topic: %s, value: %s", msg.Partition, msg.Key, msg.Topic, msg.Value))
}
kc.deal(msg)
}
}(part)
case <-stop:
kc.consumer.Close()
return
}
}
}
func (kc *KafkaConsumer) deal(msg *sarama.ConsumerMessage) {
var handlerList []IHandler
msgKey := string(msg.Key)
if l, ok := kc.handler[msgKey]; ok {
handlerList = append(handlerList, l...)
}
if msgKey != "" {
if l, ok := kc.handler[""]; ok {
handlerList = append(handlerList, l...)
}
}
if len(handlerList) == 0 {
ilog.Error(fmt.Sprintf("message key [%s] has not matched handler", msg.Key))
} else {
for _, h := range handlerList {
err := h.DealMessage(msg.Topic, msg.Partition, msg.Value)
if err == nil {
kc.consumer.MarkOffset(msg, "") // mark message as processed
}
}
}
}
//KafkaConsumer stop
func (kc *KafkaConsumer) stop(stop chan bool) {
for {
select {
case <- kc.Ctx.Done():
ilog.Info("kafka consumer stop ...")
stop <- true
ilog.Info("kafka consumer stop success")
return
}
}
}