-
Notifications
You must be signed in to change notification settings - Fork 0
/
queues.go
65 lines (52 loc) · 1.01 KB
/
queues.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
package queue
import (
"fmt"
"sync"
"github.com/go-redis/redis/v8"
)
type Options struct {
RedisClient *redis.Client
}
type Queue[T any] struct {
driver list[T]
queueName string
capacity int64
m *sync.Mutex
}
func New[T any](driverName string, queueName string, opts Options) *Queue[T] {
var driver list[T]
switch driverName {
default:
fallthrough
case "array":
driver = &array[T]{}
case "redis":
driver = newRedisList[T](queueName, opts.RedisClient)
}
return &Queue[T]{
driver: driver,
capacity: 1000,
m: &sync.Mutex{},
}
}
func (q *Queue[T]) enqueue(data T) error {
q.m.Lock()
defer q.m.Unlock()
if q.capacity == q.driver.Size() {
return fmt.Errorf("queue is full")
}
return q.driver.Append(data)
}
func (q *Queue[T]) dequeue() (item T, err error) {
q.m.Lock()
defer q.m.Unlock()
if q.driver.Size() == 0 {
return item, fmt.Errorf("queue is empty")
}
return q.driver.Detach()
}
func (q *Queue[T]) Flush() error {
q.m.Lock()
defer q.m.Unlock()
return q.driver.Flush()
}