forked from rfyiamcool/go_redis_semaphore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
go_redis_semaphore.go
198 lines (158 loc) · 3.91 KB
/
go_redis_semaphore.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
package go_redis_semaphore
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/garyburd/redigo/redis"
)
const (
PREFIX_KYE = "redis_semaphore_"
VERSION = "v0.1"
)
type Semaphore struct {
Limit int
InitLockTimeout int
ScanLock *sync.RWMutex
ScanInterval int // 每 多少秒 扫描一次
ScanTimeout int // 多少算超时
LastScanTs time.Time
RedisClient *redis.Pool
NameSpace string
QueueName string
LockName string
TokenTsHashName string
Tokens []string
}
// NameSpace 推荐使用 自增的version版本号,不然会出现更改limit出现阈值不准的问题.
func NewRedisSemaphore(redis_client *redis.Pool, limit int, namespace string) *Semaphore {
return &Semaphore{
Limit: limit,
ScanLock: new(sync.RWMutex),
InitLockTimeout: 30,
ScanInterval: 5,
ScanTimeout: 3,
RedisClient: redis_client,
NameSpace: namespace,
QueueName: namespace + "_" + "queue",
LockName: namespace + "_" + "lock",
TokenTsHashName: namespace + "_" + "hash",
LastScanTs: time.Now(),
}
}
func (s *Semaphore) Init() {
rc := s.RedisClient.Get()
defer rc.Close()
var tmp_token string
ok, _ := s.TryLock(0)
if !ok {
fmt.Println("lock failed")
return
}
// clean old token list
// to do: pipeline
rc.Do("DEL", s.QueueName)
for i := 1; i <= s.Limit; i++ {
tmp_token = fmt.Sprintf("token_seq_%d", i)
s.Push(tmp_token)
s.Tokens = append(s.Tokens, tmp_token)
}
// del lock
// rc.Do("DEL", s.LockName)
}
func (s *Semaphore) ScanIsContinue() bool {
now := time.Now()
if int(now.Sub(s.LastScanTs).Seconds()) < s.ScanInterval {
return false
}
return true
}
func (s *Semaphore) ScanTimeoutToken() []string {
rc := s.RedisClient.Get()
defer rc.Close()
expire_tokens := []string{}
s.ScanLock.Lock()
if !s.ScanIsContinue() {
s.ScanLock.Unlock()
return expire_tokens
}
res, _ := redis.StringMap(rc.Do("HGETALL", s.TokenTsHashName))
for token, ts_s := range res {
ts, _ := strconv.Atoi(ts_s)
diff_ts := time.Now().Sub(time.Unix(int64(ts), 0))
if int(diff_ts.Seconds()) > s.ScanTimeout {
expire_tokens = append(expire_tokens, token)
}
}
s.LastScanTs = time.Now()
s.ScanLock.Unlock()
return expire_tokens
}
func (s *Semaphore) TryLock(timeout int) (bool, error) {
rc := s.RedisClient.Get()
defer rc.Close()
var err error
if timeout == 0 {
_, err = redis.String(rc.Do("SET", s.LockName, "locked", "NX"))
} else {
_, err = redis.String(rc.Do("SET", s.LockName, "locked", "EX", s.InitLockTimeout, "NX"))
}
if err == redis.ErrNil {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
func (s *Semaphore) Acquire(timeout int) (string, error) {
var token string
var err error
s.ScanTimeoutToken()
if timeout > 0 {
token, err = s.PopBlock(timeout)
} else {
token, err = s.Pop()
}
return token, err
}
func (s *Semaphore) Release(token string) {
s.Push(token)
}
func (s *Semaphore) Pop() (string, error) {
rc := s.RedisClient.Get()
defer rc.Close()
res, err := redis.String(rc.Do("LPOP", s.QueueName))
// 允许队列为空值
if err == redis.ErrNil {
err = nil
}
rc.Do("HSET", s.TokenTsHashName, res, time.Now().Unix())
return res, err
}
func (s *Semaphore) Push(body string) (int, error) {
rc := s.RedisClient.Get()
defer rc.Close()
// to do: pipeline
res, err := redis.Int(rc.Do("RPUSH", s.QueueName, body))
rc.Do("HDEL", s.TokenTsHashName, body)
return res, err
}
func (s *Semaphore) PopBlock(timeout int) (string, error) {
rc := s.RedisClient.Get()
defer rc.Close()
// refer: https://gowalker.org/github.com/BPing/Golib/cache/mredis#RedisPool_BLPop
res_map, err := redis.StringMap(rc.Do("BLPOP", s.QueueName, timeout))
// 允许队列为空值
if err == redis.ErrNil {
err = nil
}
res, ok := res_map[s.QueueName]
if res != "" {
rc.Do("HSET", s.TokenTsHashName, res, time.Now().Unix())
}
if !ok {
return "", err
}
return res, err
}