-
Notifications
You must be signed in to change notification settings - Fork 51
/
consumer.go
300 lines (243 loc) · 7.9 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package rocketmq
import (
"fmt"
"github.com/golang/glog"
"net"
"os"
"strconv"
"sync/atomic"
"time"
)
const (
BrokerSuspendMaxTimeMillis = 1000 * 15
FLAG_COMMIT_OFFSET int32 = 0x1 << 0
FLAG_SUSPEND int32 = 0x1 << 1
FLAG_SUBSCRIPTION int32 = 0x1 << 2
FLAG_CLASS_FILTER int32 = 0x1 << 3
)
type MessageListener func(msgs []*MessageExt) error
var DEFAULT_IP = GetLocalIp4()
type Config struct {
Nameserver string
ClientIp string
InstanceName string
}
type Consumer interface {
//Admin
Start() error
Shutdown()
RegisterMessageListener(listener MessageListener)
Subscribe(topic string, subExpression string)
UnSubcribe(topic string)
SendMessageBack(msg MessageExt, delayLevel int) error
SendMessageBack1(msg MessageExt, delayLevel int, brokerName string) error
fetchSubscribeMessageQueues(topic string) error
}
type DefaultConsumer struct {
conf *Config
consumerGroup string
consumeFromWhere string
consumerType string
messageModel string
unitMode bool
subscription map[string]string
messageListener MessageListener
offsetStore OffsetStore
brokers map[string]net.Conn
rebalance *Rebalance
remotingClient RemotingClient
mqClient *MqClient
}
func NewDefaultConsumer(name string, conf *Config) (Consumer, error) {
if conf == nil {
conf = &Config{
Nameserver: os.Getenv("ROCKETMQ_NAMESVR"),
InstanceName: "DEFAULT",
}
}
if conf.ClientIp == "" {
conf.ClientIp = DEFAULT_IP
}
remotingClient := NewDefaultRemotingClient()
mqClient := NewMqClient()
rebalance := NewRebalance()
rebalance.groupName = name
rebalance.mqClient = mqClient
offsetStore := new(RemoteOffsetStore)
offsetStore.mqClient = mqClient
offsetStore.groupName = name
offsetStore.offsetTable = make(map[MessageQueue]int64)
pullMessageService := NewPullMessageService()
consumer := &DefaultConsumer{
conf: conf,
consumerGroup: name,
consumeFromWhere: "CONSUME_FROM_LAST_OFFSET",
subscription: make(map[string]string),
offsetStore: offsetStore,
brokers: make(map[string]net.Conn),
rebalance: rebalance,
remotingClient: remotingClient,
mqClient: mqClient,
}
mqClient.consumerTable[name] = consumer
mqClient.remotingClient = remotingClient
mqClient.conf = conf
mqClient.clientId = conf.ClientIp + "@" + strconv.Itoa(os.Getpid())
mqClient.pullMessageService = pullMessageService
rebalance.consumer = consumer
pullMessageService.consumer = consumer
return consumer, nil
}
func (self *DefaultConsumer) Start() error {
self.mqClient.start()
return nil
}
func (self *DefaultConsumer) Shutdown() {
}
func (self *DefaultConsumer) RegisterMessageListener(messageListener MessageListener) {
self.messageListener = messageListener
}
func (self *DefaultConsumer) Subscribe(topic string, subExpression string) {
self.subscription[topic] = subExpression
subData := &SubscriptionData{
Topic: topic,
SubString: subExpression,
}
self.rebalance.subscriptionInner[topic] = subData
}
func (self *DefaultConsumer) UnSubcribe(topic string) {
delete(self.subscription, topic)
}
func (self *DefaultConsumer) SendMessageBack(msg MessageExt, delayLevel int) error {
return nil
}
func (self *DefaultConsumer) SendMessageBack1(msg MessageExt, delayLevel int, brokerName string) error {
return nil
}
func (self *DefaultConsumer) fetchSubscribeMessageQueues(topic string) error {
return nil
}
func (self *DefaultConsumer) pullMessage(pullRequest *PullRequest) {
commitOffsetEnable := false
commitOffsetValue := int64(0)
commitOffsetValue = self.offsetStore.readOffset(pullRequest.messageQueue, READ_FROM_MEMORY)
if commitOffsetValue > 0 {
commitOffsetEnable = true
}
var sysFlag int32 = 0
if commitOffsetEnable {
sysFlag |= FLAG_COMMIT_OFFSET
}
sysFlag |= FLAG_SUSPEND
subscriptionData, ok := self.rebalance.subscriptionInner[pullRequest.messageQueue.topic]
var subVersion int64
var subString string
if ok {
subVersion = subscriptionData.SubVersion
subString = subscriptionData.SubString
sysFlag |= FLAG_SUBSCRIPTION
}
requestHeader := new(PullMessageRequestHeader)
requestHeader.ConsumerGroup = pullRequest.consumerGroup
requestHeader.Topic = pullRequest.messageQueue.topic
requestHeader.QueueId = pullRequest.messageQueue.queueId
requestHeader.QueueOffset = pullRequest.nextOffset
requestHeader.SysFlag = sysFlag
requestHeader.CommitOffset = commitOffsetValue
requestHeader.SuspendTimeoutMillis = BrokerSuspendMaxTimeMillis
if ok {
requestHeader.SubVersion = subVersion
requestHeader.Subscription = subString
}
pullCallback := func(responseFuture *ResponseFuture) {
var nextBeginOffset int64 = pullRequest.nextOffset
if responseFuture != nil {
responseCommand := responseFuture.responseCommand
if responseCommand.Code == SUCCESS && len(responseCommand.Body) > 0 {
var err error
pullResult, ok := responseCommand.ExtFields.(map[string]interface{})
if ok {
if nextBeginOffsetInter, ok := pullResult["nextBeginOffset"]; ok {
if nextBeginOffsetStr, ok := nextBeginOffsetInter.(string); ok {
nextBeginOffset, err = strconv.ParseInt(nextBeginOffsetStr, 10, 64)
if err != nil {
glog.Error(err)
return
}
}
}
}
msgs := decodeMessage(responseFuture.responseCommand.Body)
err = self.messageListener(msgs)
if err != nil {
glog.Error(err)
//TODO retry
} else {
self.offsetStore.updateOffset(pullRequest.messageQueue, nextBeginOffset, false)
}
} else if responseCommand.Code == PULL_NOT_FOUND {
} else if responseCommand.Code == PULL_RETRY_IMMEDIATELY || responseCommand.Code == PULL_OFFSET_MOVED {
glog.Errorf("pull message error,code=%d,request=%v", responseCommand.Code,requestHeader)
var err error
pullResult, ok := responseCommand.ExtFields.(map[string]interface{})
if ok {
if nextBeginOffsetInter, ok := pullResult["nextBeginOffset"]; ok {
if nextBeginOffsetStr, ok := nextBeginOffsetInter.(string); ok {
nextBeginOffset, err = strconv.ParseInt(nextBeginOffsetStr, 10, 64)
if err != nil {
glog.Error(err)
}
}
}
}
//time.Sleep(1 * time.Second)
} else {
glog.Error(fmt.Sprintf("pull message error,code=%d,body=%s", responseCommand.Code, string(responseCommand.Body)))
glog.Error(pullRequest.messageQueue)
time.Sleep(1 * time.Second)
}
} else {
glog.Error("responseFuture is nil")
}
nextPullRequest := &PullRequest{
consumerGroup: pullRequest.consumerGroup,
nextOffset: nextBeginOffset,
messageQueue: pullRequest.messageQueue,
}
self.mqClient.pullMessageService.pullRequestQueue <- nextPullRequest
}
brokerAddr, _, found := self.mqClient.findBrokerAddressInSubscribe(pullRequest.messageQueue.brokerName, 0, false)
if found {
currOpaque := atomic.AddInt32(&opaque, 1)
remotingCommand := new(RemotingCommand)
remotingCommand.Code = PULL_MESSAGE
remotingCommand.Opaque = currOpaque
remotingCommand.Flag = 0
remotingCommand.Language = "JAVA"
remotingCommand.Version = 79
remotingCommand.ExtFields = requestHeader
self.remotingClient.invokeAsync(brokerAddr, remotingCommand, 1000, pullCallback)
}
}
func (self *DefaultConsumer) updateTopicSubscribeInfo(topic string, info []*MessageQueue) {
if self.rebalance.subscriptionInner != nil {
self.rebalance.subscriptionInnerLock.RLock()
_, ok := self.rebalance.subscriptionInner[topic]
self.rebalance.subscriptionInnerLock.RUnlock()
if ok {
self.rebalance.subscriptionInnerLock.Lock()
self.rebalance.topicSubscribeInfoTable[topic] = info
self.rebalance.subscriptionInnerLock.Unlock()
}
}
}
func (self *DefaultConsumer) subscriptions() []*SubscriptionData {
subscriptions := make([]*SubscriptionData, 0)
for _, subscription := range self.rebalance.subscriptionInner {
subscriptions = append(subscriptions, subscription)
}
return subscriptions
}
func (self *DefaultConsumer) doRebalance() {
self.rebalance.doRebalance()
}