-
Notifications
You must be signed in to change notification settings - Fork 5
/
redis.go
210 lines (185 loc) · 4.38 KB
/
redis.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
package redisdb
import (
"context"
"encoding/json"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/golang-queue/queue"
"github.com/golang-queue/queue/core"
"github.com/golang-queue/queue/job"
"github.com/redis/go-redis/v9"
)
var _ core.Worker = (*Worker)(nil)
// Worker for Redis
type Worker struct {
// redis config
rdb redis.Cmdable
tasks chan redis.XMessage
stopFlag int32
stopOnce sync.Once
startOnce sync.Once
stop chan struct{}
exit chan struct{}
opts options
}
// NewWorker for struc
func NewWorker(opts ...Option) *Worker {
var err error
w := &Worker{
opts: newOptions(opts...),
stop: make(chan struct{}),
exit: make(chan struct{}),
tasks: make(chan redis.XMessage),
}
if w.opts.connectionString != "" {
options, err := redis.ParseURL(w.opts.connectionString)
if err != nil {
w.opts.logger.Fatal(err)
}
w.rdb = redis.NewClient(options)
} else if w.opts.addr != "" {
if w.opts.cluster {
w.rdb = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: strings.Split(w.opts.addr, ","),
Password: w.opts.password,
})
} else {
options := &redis.Options{
Addr: w.opts.addr,
Password: w.opts.password,
DB: w.opts.db,
}
w.rdb = redis.NewClient(options)
}
}
_, err = w.rdb.Ping(context.Background()).Result()
if err != nil {
w.opts.logger.Fatal(err)
}
return w
}
func (w *Worker) startConsumer() {
w.startOnce.Do(func() {
if err := w.rdb.XGroupCreateMkStream(
context.Background(),
w.opts.streamName,
w.opts.group,
"$",
).Err(); err != nil {
w.opts.logger.Error(err)
}
go w.fetchTask()
})
}
func (w *Worker) fetchTask() {
for {
select {
case <-w.stop:
return
default:
}
ctx := context.Background()
data, err := w.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: w.opts.group,
Consumer: w.opts.consumer,
Streams: []string{w.opts.streamName, ">"},
// count is number of entries we want to read from redis
Count: 1,
// we use the block command to make sure if no entry is found we wait
// until an entry is found
Block: w.opts.blockTime,
}).Result()
if err != nil {
w.opts.logger.Errorf("error while reading from redis %v", err)
continue
}
// we have received the data we should loop it and queue the messages
// so that our tasks can start processing
for _, result := range data {
for _, message := range result.Messages {
select {
case w.tasks <- message:
if err := w.rdb.XAck(ctx, w.opts.streamName, w.opts.group, message.ID).Err(); err != nil {
w.opts.logger.Errorf("can't ack message: %s", message.ID)
}
case <-w.stop:
// Todo: re-queue the task
w.opts.logger.Info("re-queue the task: ", message.ID)
if err := w.queue(message.Values); err != nil {
w.opts.logger.Error("error to re-queue the task: ", message.ID)
}
close(w.exit)
return
}
}
}
}
}
// Shutdown worker
func (w *Worker) Shutdown() error {
if !atomic.CompareAndSwapInt32(&w.stopFlag, 0, 1) {
return queue.ErrQueueShutdown
}
w.stopOnce.Do(func() {
close(w.stop)
// wait requeue
select {
case <-w.exit:
case <-time.After(200 * time.Millisecond):
}
switch v := w.rdb.(type) {
case *redis.Client:
v.Close()
case *redis.ClusterClient:
v.Close()
}
close(w.tasks)
})
return nil
}
func (w *Worker) queue(data interface{}) error {
ctx := context.Background()
// Publish a message.
err := w.rdb.XAdd(ctx, &redis.XAddArgs{
Stream: w.opts.streamName,
MaxLen: w.opts.maxLength,
Values: data,
}).Err()
return err
}
// Queue send notification to queue
func (w *Worker) Queue(task core.QueuedMessage) error {
if atomic.LoadInt32(&w.stopFlag) == 1 {
return queue.ErrQueueShutdown
}
return w.queue(map[string]interface{}{"body": BytesToStr(task.Bytes())})
}
// Run start the worker
func (w *Worker) Run(ctx context.Context, task core.QueuedMessage) error {
return w.opts.runFunc(ctx, task)
}
// Request a new task
func (w *Worker) Request() (core.QueuedMessage, error) {
clock := 0
w.startConsumer()
loop:
for {
select {
case task, ok := <-w.tasks:
if !ok {
return nil, queue.ErrQueueHasBeenClosed
}
var data job.Message
_ = json.Unmarshal(StrToBytes(task.Values["body"].(string)), &data)
return &data, nil
case <-time.After(1 * time.Second):
if clock == 5 {
break loop
}
clock += 1
}
}
return nil, queue.ErrNoTaskInQueue
}