-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsumer.go
267 lines (225 loc) · 4.77 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
package redis
import (
"fmt"
"log"
"sync"
"time"
redis "github.com/go-redis/redis/v7"
)
type Consumer struct {
Group string
Name string
RedisOption *redis.UniversalOptions
MaxInFlight int64
MaxPollingTimeout time.Duration
ClaimMinIdleTime time.Duration
IdlingTimeout time.Duration // 若沒有任何訊息時等待多久
ClaimSensitivity int // Read 時取得的訊息數小於 n 的話, 執行 Claim
ClaimOccurrenceRate int32 // Read 每執行 n 次後 執行 Claim 1 次
MessageHandler MessageHandleProc
ErrorHandler ErrorHandleProc
Logger *log.Logger
client *consumerClient
stopChan chan bool
wg sync.WaitGroup
claimTrigger *CyclicCounter
mutex sync.Mutex
initialized bool
running bool
disposed bool
}
func (c *Consumer) Subscribe(streams ...StreamOffsetInfo) error {
if c.disposed {
return fmt.Errorf("the Consumer has been disposed")
}
if c.running {
return fmt.Errorf("the Consumer is running")
}
var err error
c.mutex.Lock()
defer func() {
if err != nil {
c.running = false
c.disposed = true
}
c.mutex.Unlock()
}()
if len(streams) == 0 {
return nil
}
c.init()
c.running = true
// new consumer
{
consumer := &consumerClient{
Group: c.Group,
Name: c.Name,
RedisOption: c.RedisOption,
}
err = consumer.subscribe(streams...)
if err != nil {
return err
}
c.client = consumer
}
// reset
c.claimTrigger.reset()
c.wg.Add(1)
go func() {
defer c.wg.Done()
defer c.client.close()
for {
select {
case <-c.stopChan:
return
default:
err := c.processMessage()
if err != nil {
if !c.processError(err) {
c.Logger.Fatalf("%% Error: %v\n", err)
return
}
}
}
}
}()
return nil
}
func (c *Consumer) Close() {
if c.disposed {
return
}
c.mutex.Lock()
defer func() {
c.running = false
c.disposed = true
c.mutex.Unlock()
}()
if c.stopChan != nil {
c.stopChan <- true
close(c.stopChan)
}
c.wg.Wait()
}
func (c *Consumer) Pause(streams ...string) error {
return c.client.pause(streams...)
}
func (c *Consumer) Resume(streams ...string) error {
return c.client.resume(streams...)
}
func (c *Consumer) init() {
if c.initialized {
return
}
if c.stopChan == nil {
c.stopChan = make(chan bool, 1)
}
if c.claimTrigger == nil {
c.claimTrigger = newCyclicCounter(c.ClaimOccurrenceRate)
}
if c.Logger == nil {
c.Logger = defaultLogger
}
c.initialized = true
}
func (c *Consumer) processError(err error) (disposed bool) {
if c.ErrorHandler != nil {
consumerErr := &ConsumerError{
err: err,
}
return c.ErrorHandler(consumerErr)
}
return false
}
func (c *Consumer) processMessage() error {
var (
readMessages int = 0
)
// perform XREADGROUP
{
streams, err := c.client.read(c.MaxInFlight, c.MaxPollingTimeout)
if err != nil {
if err != redis.Nil {
return err
}
}
if len(streams) > 0 {
for _, stream := range streams {
for _, message := range stream.Messages {
c.handleMessage(stream.Stream, &message)
readMessages++
}
}
}
}
// perform XAUTOCLAIM
if c.claimTrigger.spin() || readMessages < c.ClaimSensitivity {
// fmt.Println("***CLAIM")
var (
pendingFetchingSize = c.computePendingFetchingSize(c.MaxInFlight)
)
streams, err := c.client.claim(c.ClaimMinIdleTime, c.MaxInFlight, pendingFetchingSize)
if err != nil {
if err != redis.Nil {
return err
}
}
if len(streams) > 0 {
for _, stream := range streams {
for _, message := range stream.Messages {
c.handleMessage(stream.Stream, &message)
}
}
return nil
}
if readMessages == 0 {
time.Sleep(c.IdlingTimeout)
}
}
return nil
}
func (c *Consumer) computePendingFetchingSize(maxInFlight int64) int64 {
var (
fetchingSize = maxInFlight * PENDING_FETCHING_SIZE_COEFFICIENT
)
if fetchingSize < MIN_PENDING_FETCHING_SIZE {
return MIN_PENDING_FETCHING_SIZE
}
if fetchingSize > MAX_PENDING_FETCHING_SIZE {
return MAX_PENDING_FETCHING_SIZE
}
return fetchingSize
}
func (c *Consumer) handleMessage(stream string, m *redis.XMessage) {
msg := Message{
XMessage: m,
ConsumerGroup: c.Group,
Stream: stream,
Delegate: &clientMessageDelegate{client: c},
}
c.MessageHandler(&msg)
}
func (c *Consumer) doAck(m *Message) {
if c.disposed {
return
}
if !c.running {
return
}
_, err := c.client.ack(m.Stream, m.ID)
if err != nil {
c.Logger.Printf("error sending command XACK '%s' '%s' '%s'", m.Stream, c.Group, m.ID)
}
}
func (c *Consumer) doDel(m *Message) {
if c.disposed {
return
}
if !c.running {
return
}
_, err := c.client.del(m.Stream, m.ID)
if err != nil {
c.Logger.Printf("error sending command XACK '%s' '%s'", m.Stream, m.ID)
}
}