github.com/lingyao2333/mo-zero@v1.4.1/core/stores/redis/scriptcache.go (about) 1 package redis 2 3 import ( 4 "sync" 5 "sync/atomic" 6 ) 7 8 var ( 9 once sync.Once 10 lock sync.Mutex 11 instance *ScriptCache 12 ) 13 14 type ( 15 // Map is an alias of map[string]string. 16 Map map[string]string 17 18 // A ScriptCache is a cache that stores a script with its sha key. 19 ScriptCache struct { 20 atomic.Value 21 } 22 ) 23 24 // GetScriptCache returns a ScriptCache. 25 func GetScriptCache() *ScriptCache { 26 once.Do(func() { 27 instance = &ScriptCache{} 28 instance.Store(make(Map)) 29 }) 30 31 return instance 32 } 33 34 // GetSha returns the sha string of given script. 35 func (sc *ScriptCache) GetSha(script string) (string, bool) { 36 cache := sc.Load().(Map) 37 ret, ok := cache[script] 38 return ret, ok 39 } 40 41 // SetSha sets script with sha into the ScriptCache. 42 func (sc *ScriptCache) SetSha(script, sha string) { 43 lock.Lock() 44 defer lock.Unlock() 45 46 cache := sc.Load().(Map) 47 newCache := make(Map) 48 for k, v := range cache { 49 newCache[k] = v 50 } 51 newCache[script] = sha 52 sc.Store(newCache) 53 }