/
string_store.go
148 lines (124 loc) · 2.59 KB
/
string_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
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
package driver
import (
"context"
"sync"
"time"
)
/**
@author : Jerbe - The porter from Earth
@time : 2023/9/8 17:50
@describe :
*/
// stringValue 字符串值
type stringValue struct {
expireValue
// value 值
value string
}
func newStringValue() *stringValue {
defaultExpireAt := time.Now().Add(ValueMaxTTL)
return &stringValue{
expireValue: expireValue{
expireAt: &defaultExpireAt,
expired: false,
},
}
}
type stringStore struct {
baseStore
}
func newStringStore() *stringStore {
ticker := time.NewTicker(time.Second * 10)
store := &stringStore{
baseStore: baseStore{
values: make(map[string]expireable),
rwMutex: sync.RWMutex{},
expireTicker: ticker,
},
}
// 定时检测到期key
go store.checkExpireTick()
return store
}
func (s *stringStore) Type() driverStoreType {
return driverStoreTypeString
}
// Set 设置数据
func (ss *stringStore) Set(ctx context.Context, key, data string, expiration time.Duration) error {
ss.rwMutex.Lock()
defer ss.rwMutex.Unlock()
select {
case <-ctx.Done():
return ctx.Err()
default:
val, ok := ss.values[key].(*stringValue)
if !ok {
val = newStringValue()
}
val.value = data
if ok && expiration != KeepTTL {
val.SetExpire(expiration)
}
ss.values[key] = val
}
return nil
}
// SetNX 设置数据,如果key不存在的话
func (ss *stringStore) SetNX(ctx context.Context, key, data string, expiration time.Duration) (bool, error) {
ss.rwMutex.Lock()
defer ss.rwMutex.Unlock()
select {
case <-ctx.Done():
return false, ctx.Err()
default:
val, ok := ss.values[key].(*stringValue)
if ok {
return false, nil
}
val = newStringValue()
val.value = data
if ok && expiration != KeepTTL {
val.SetExpire(expiration)
}
ss.values[key] = val
return true, nil
}
}
// Get 获取数据
func (ss *stringStore) Get(ctx context.Context, key string) (string, error) {
ss.rwMutex.RLock()
defer ss.rwMutex.RUnlock()
select {
case <-ctx.Done():
return "", nil
default:
d, ok := ss.values[key]
if !ok {
return "", MemoryNil
}
if d.IsExpire() {
return "", MemoryNil
}
return d.(*stringValue).value, nil
}
}
// MGet 根据多个Key获取多个值
func (ss *stringStore) MGet(ctx context.Context, keys ...string) ([]interface{}, error) {
ss.rwMutex.RLock()
defer ss.rwMutex.RUnlock()
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
var rst = make([]interface{}, len(keys), len(keys))
for i, key := range keys {
if d, ok := ss.values[key]; ok {
if d.IsExpire() {
continue
}
rst[i] = d.(*stringValue).value
}
}
return rst, nil
}
}