@@ -16,12 +16,14 @@ var _ queue.Worker = (*Worker)(nil)
16
16
17
17
// Worker for NSQ
18
18
type Worker struct {
19
- client * nats.Conn
20
- stop chan struct {}
21
- stopFlag int32
22
- stopOnce sync.Once
23
- opts options
24
- tasks chan * nats.Msg
19
+ client * nats.Conn
20
+ stop chan struct {}
21
+ exit chan struct {}
22
+ stopFlag int32
23
+ stopOnce sync.Once
24
+ opts options
25
+ subscription * nats.Subscription
26
+ tasks chan * nats.Msg
25
27
}
26
28
27
29
// NewWorker for struc
@@ -30,6 +32,7 @@ func NewWorker(opts ...Option) *Worker {
30
32
w := & Worker {
31
33
opts : newOptions (opts ... ),
32
34
stop : make (chan struct {}),
35
+ exit : make (chan struct {}),
33
36
tasks : make (chan * nats.Msg , 1 ),
34
37
}
35
38
@@ -46,13 +49,18 @@ func NewWorker(opts ...Option) *Worker {
46
49
}
47
50
48
51
func (w * Worker ) startConsumer () error {
49
- _ , err := w .client .QueueSubscribe (w .opts .subj , w .opts .queue , func (msg * nats.Msg ) {
52
+ var err error
53
+ w .subscription , err = w .client .QueueSubscribe (w .opts .subj , w .opts .queue , func (msg * nats.Msg ) {
50
54
select {
51
55
case w .tasks <- msg :
52
56
case <- w .stop :
53
57
if msg != nil {
54
58
// re-queue the job if worker has been shutdown.
55
59
w .opts .logger .Info ("re-queue the old job" )
60
+ if err := w .client .Publish (w .opts .subj , msg .Data ); err != nil {
61
+ panic (err )
62
+ }
63
+ close (w .exit )
56
64
}
57
65
}
58
66
})
@@ -125,7 +133,12 @@ func (w *Worker) Shutdown() error {
125
133
}
126
134
127
135
w .stopOnce .Do (func () {
136
+ _ = w .subscription .Unsubscribe ()
128
137
close (w .stop )
138
+ select {
139
+ case <- w .exit :
140
+ case <- time .After (50 * time .Millisecond ):
141
+ }
129
142
w .client .Close ()
130
143
close (w .tasks )
131
144
})
0 commit comments