forked from infinilabs/framework
/
queue.go
126 lines (102 loc) · 2.35 KB
/
queue.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
package queue
import (
"errors"
log "github.com/cihub/seelog"
"github.com/infinitbyte/framework/core/config"
"github.com/infinitbyte/framework/core/global"
"github.com/infinitbyte/framework/core/queue"
. "github.com/infinitbyte/framework/modules/queue/disk_queue"
"os"
"path"
"strings"
"sync"
"time"
)
var queues map[string]*BackendQueue
type DiskQueue struct {
}
func (module DiskQueue) Name() string {
return "Queue"
}
var initLocker sync.Mutex
func initQueue(name string) error {
channel := "default"
if queues[name] != nil {
return nil
}
initLocker.Lock()
defer initLocker.Unlock()
//double check after lock in
if queues[name] != nil {
return nil
}
log.Debugf("init queue,%s", name)
dataPath := path.Join(global.Env().GetWorkingDir(), "queue", strings.ToLower(name))
os.MkdirAll(dataPath, 0777)
readBuffSize := 0
syncTimeout := 5 * time.Second
var syncEvery int64 = 2500
//TODO parameter
q := NewDiskQueue(strings.ToLower(channel), dataPath, 100*1024*1024, 1, 1<<25, syncEvery, syncTimeout, readBuffSize)
queues[name] = &q
return nil
}
func (module DiskQueue) Setup(cfg *config.Config) {
queues = make(map[string]*BackendQueue)
queue.Register("disk", module)
}
func (module DiskQueue) Push(k string, v []byte) error {
initQueue(k)
return (*queues[k]).Put(v)
}
func (module DiskQueue) ReadChan(k string) chan []byte {
initQueue(k)
return (*queues[k]).ReadChan()
}
func (module DiskQueue) Pop(k string, timeoutInSeconds time.Duration) ([]byte, error) {
initQueue(k)
if timeoutInSeconds > 0 {
timeout := make(chan bool, 1)
go func() {
time.Sleep(timeoutInSeconds) // sleep 3 second
timeout <- true
}()
select {
case b := <-(*queues[k]).ReadChan():
return b, nil
case <-timeout:
return nil, errors.New("time out")
}
} else {
b := <-(*queues[k]).ReadChan()
return b, nil
}
}
func (module DiskQueue) Close(k string) error {
b := (*queues[k]).Close()
return b
}
func (module DiskQueue) Depth(k string) int64 {
initQueue(k)
b := (*queues[k]).Depth()
return b
}
func (module DiskQueue) GetQueues() []string {
result := []string{}
for k := range queues {
result = append(result, k)
}
return result
}
func (module DiskQueue) Start() error {
return nil
}
func (module DiskQueue) Stop() error {
for _, v := range queues {
err := (*v).Close()
if err != nil {
log.Debug(err)
}
}
return nil
}