forked from zeromicro/go-queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumernode.go
94 lines (81 loc) · 2.04 KB
/
consumernode.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
package dq
import (
"time"
"github.com/beanstalkd/go-beanstalk"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
)
type (
consumerNode struct {
conn *connection
tube string
on *syncx.AtomicBool
}
consumeService struct {
c *consumerNode
consume Consume
}
)
func newConsumerNode(endpoint, tube string) *consumerNode {
return &consumerNode{
conn: newConnection(endpoint, tube),
tube: tube,
on: syncx.ForAtomicBool(true),
}
}
func (c *consumerNode) dispose() {
c.on.Set(false)
}
func (c *consumerNode) consumeEvents(consume Consume) {
for c.on.True() {
conn, err := c.conn.get()
if err != nil {
logx.Error(err)
time.Sleep(time.Second)
continue
}
// because getting conn takes at most one second, reserve tasks at most 5 seconds,
// if don't check on/off here, the conn might not be closed due to
// graceful shutdon waits at most 5.5 seconds.
if !c.on.True() {
break
}
conn.Tube.Name = c.tube
conn.TubeSet.Name[c.tube] = true
id, body, err := conn.Reserve(reserveTimeout)
if err == nil {
conn.Delete(id)
consume(body)
continue
}
// the error can only be beanstalk.NameError or beanstalk.ConnError
switch cerr := err.(type) {
case beanstalk.ConnError:
switch cerr.Err {
case beanstalk.ErrTimeout:
// timeout error on timeout, just continue the loop
case beanstalk.ErrBadChar, beanstalk.ErrBadFormat, beanstalk.ErrBuried, beanstalk.ErrDeadline,
beanstalk.ErrDraining, beanstalk.ErrEmpty, beanstalk.ErrInternal, beanstalk.ErrJobTooBig,
beanstalk.ErrNoCRLF, beanstalk.ErrNotFound, beanstalk.ErrNotIgnored, beanstalk.ErrTooLong:
// won't reset
logx.Error(err)
default:
// beanstalk.ErrOOM, beanstalk.ErrUnknown and other errors
logx.Error(err)
c.conn.reset()
time.Sleep(time.Second)
}
default:
logx.Error(err)
}
}
if err := c.conn.Close(); err != nil {
logx.Error(err)
}
}
func (cs consumeService) Start() {
cs.c.consumeEvents(cs.consume)
}
func (cs consumeService) Stop() {
cs.c.dispose()
}