-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis_store.go
63 lines (53 loc) · 1.15 KB
/
redis_store.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
package ratelimiter
import (
"context"
"time"
"github.com/go-redis/redis/v8"
)
const REDIS_STORE_PREFIX = "go-rm-"
type redisStore struct {
Store
count int64
duration time.Duration
// sync.RWMutex
limit int64
key string
rdb *redis.Client
ctx context.Context
}
func (m *redisStore) init(key string, limit int64, window time.Duration, config RateLimiterConfig) {
m.count = 0
m.duration = window
m.limit = limit
m.key = REDIS_STORE_PREFIX + key
m.rdb = config.Rdb
if config.Ctx != nil {
m.ctx = config.Ctx
} else {
m.ctx = context.Background()
}
}
func (m *redisStore) getStatus() (int64, bool, error) {
// m.RLock()
// defer m.RUnlock()
count, err := m.rdb.Get(m.ctx, m.key).Int64()
if err != nil {
return 0, false, err
} else {
return count, count < m.limit, nil
}
}
func (m *redisStore) incrementAndCheck() (bool, error) {
result, err := m.rdb.Incr(m.ctx, m.key).Result()
if err != nil {
return false, err
}
if result == 1 {
// This is the first time the key is set, so set the TTL
err := m.rdb.Expire(m.ctx, m.key, m.duration).Err()
if err != nil {
return false, err
}
}
return result <= int64(m.limit), nil
}