scriptcache.go 950 B

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