-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslide_redis.go
68 lines (56 loc) · 1.29 KB
/
slide_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
package util
import (
"current-limit/common"
redigo "github.com/garyburd/redigo/redis"
"strconv"
"sync"
"time"
)
const REDIS_KEY = "slide_redis"
/**
滑动窗口计数器-集群版 基于redis
*/
type CounterRedis struct {
rate int64 //计数周期内最多允许的请求数
cycle time.Duration //计数周期
lock sync.Mutex
}
func (l *CounterRedis) Allow() bool {
l.lock.Lock()
defer l.lock.Unlock()
// 当前时间
now := time.Now().UnixNano()
redis := common.Get()
count, err := redis.Do("llen", REDIS_KEY)
if err != nil {
panic(err)
}
countList, _ := count.(int64)
if countList < l.rate {
// list没有满 插入
_, err := redis.Do("rpush", REDIS_KEY, now)
if err != nil {
panic(err)
}
return true
}
timeStart, err := redigo.Values(redis.Do("lrange", REDIS_KEY, 0, 0))
timeStartI, _ := timeStart[0].([]uint8)
timeStartS := common.B2S(timeStartI)
tint64, _ := strconv.ParseInt(timeStartS, 10, 64)
// 时间范围内 拒绝
if now-tint64 <= l.cycle.Nanoseconds() {
return false
}
// 删掉第一个 重新插入当前时间
redis.Do("lpop", REDIS_KEY)
redis.Do("rpush", REDIS_KEY, now)
return true
}
func (l *CounterRedis) Set(r int64, cycle time.Duration) {
if r <= 0 || cycle <= 0 {
panic("参数异常")
}
l.rate = r
l.cycle = cycle
}