scriptcache.go 696 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 map[string]string
  13. ScriptCache struct {
  14. atomic.Value
  15. }
  16. )
  17. func GetScriptCache() *ScriptCache {
  18. once.Do(func() {
  19. instance = &ScriptCache{}
  20. instance.Store(make(Map))
  21. })
  22. return instance
  23. }
  24. func (sc *ScriptCache) GetSha(script string) (string, bool) {
  25. cache := sc.Load().(Map)
  26. ret, ok := cache[script]
  27. return ret, ok
  28. }
  29. func (sc *ScriptCache) SetSha(script, sha string) {
  30. lock.Lock()
  31. defer lock.Unlock()
  32. cache := sc.Load().(Map)
  33. newCache := make(Map)
  34. for k, v := range cache {
  35. newCache[k] = v
  36. }
  37. newCache[script] = sha
  38. sc.Store(newCache)
  39. }