-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
scriptcache.go
53 lines (44 loc) · 950 Bytes
/
scriptcache.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
package redis
import (
"sync"
"sync/atomic"
)
var (
once sync.Once
lock sync.Mutex
instance *ScriptCache
)
type (
// Map is an alias of map[string]string.
Map map[string]string
// A ScriptCache is a cache that stores a script with its sha key.
ScriptCache struct {
atomic.Value
}
)
// GetScriptCache returns a ScriptCache.
func GetScriptCache() *ScriptCache {
once.Do(func() {
instance = &ScriptCache{}
instance.Store(make(Map))
})
return instance
}
// GetSha returns the sha string of given script.
func (sc *ScriptCache) GetSha(script string) (string, bool) {
cache := sc.Load().(Map)
ret, ok := cache[script]
return ret, ok
}
// SetSha sets script with sha into the ScriptCache.
func (sc *ScriptCache) SetSha(script, sha string) {
lock.Lock()
defer lock.Unlock()
cache := sc.Load().(Map)
newCache := make(Map)
for k, v := range cache {
newCache[k] = v
}
newCache[script] = sha
sc.Store(newCache)
}