/
check_repeat.go
62 lines (51 loc) 路 1.48 KB
/
check_repeat.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
package redis
import (
"context"
"strings"
"time"
"github.com/go-redis/redis/v8"
)
const (
// PrefixCheckRepeat check repeat key
PrefixCheckRepeat = "CHECK_REPEAT"
// RepeatDefaultTimeout define default timeout
RepeatDefaultTimeout = 60
)
// CheckRepeat define interface
type CheckRepeat interface {
Set(key string, value interface{}, expiration time.Duration) error
Get(key string) (string, error)
SetNX(key string, value interface{}, expiration time.Duration) (bool, error)
Del(keys string) int64
}
type checkRepeat struct {
client *redis.Client
}
// NewCheckRepeat create a check repeat
func NewCheckRepeat(client *redis.Client) CheckRepeat {
return &checkRepeat{
client: client,
}
}
// GetKey 鑾峰彇key
func getKey(key string) string {
return strings.Join([]string{PrefixCheckRepeat, key}, ":")
}
func (c *checkRepeat) Set(key string, value interface{}, expiration time.Duration) error {
key = getKey(key)
return c.client.Set(context.Background(), key, value, expiration).Err()
}
func (c *checkRepeat) Get(key string) (string, error) {
key = getKey(key)
return c.client.Get(context.Background(), key).Result()
}
func (c *checkRepeat) SetNX(key string, value interface{}, expiration time.Duration) (bool, error) {
key = getKey(key)
return c.client.SetNX(context.Background(), key, value, expiration).Result()
}
func (c *checkRepeat) Del(key string) int64 {
key = getKey(key)
var keys []string
keys = append(keys, key)
return c.client.Del(context.Background(), keys...).Val()
}