github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zcache/cache.go (about) 1 // Package zcache cache operation 2 package zcache 3 4 import ( 5 "errors" 6 "sync" 7 "time" 8 9 "github.com/sohaha/zlsgo/zutil" 10 ) 11 12 var ( 13 // ErrKeyNotFound ErrKeyNotFound 14 ErrKeyNotFound = errors.New("key is not in cache") 15 // ErrKeyNotFoundAndNotCallback ErrKeyNotFoundAndNotCallback 16 ErrKeyNotFoundAndNotCallback = errors.New("key is not in cache and no callback is set") 17 cache = make(map[string]*Table) 18 ite = New("defaultCache") 19 mutex sync.RWMutex 20 ) 21 22 func Set(key string, data interface{}, lifeSpan uint, interval ...bool) { 23 ite.Set(key, data, lifeSpan, interval...) 24 } 25 26 func Delete(key string) (*Item, error) { 27 return ite.Delete(key) 28 } 29 30 func Clear() { 31 ite.Clear() 32 } 33 34 func Get(key string) (value interface{}, err error) { 35 return ite.Get(key) 36 } 37 38 func GetInt(key string) (value int, err error) { 39 return ite.GetInt(key) 40 } 41 42 func GetString(key string) (value string, err error) { 43 return ite.GetString(key) 44 } 45 46 func GetT(key string) (*Item, error) { 47 return ite.GetT(key) 48 } 49 50 // MustGet get the Raw of the specified key, set if it does not exist 51 func MustGet(key string, do func(set func(data interface{}, 52 lifeSpan time.Duration, interval ...bool)) ( 53 err error)) (data interface{}, err error) { 54 return ite.MustGet(key, do) 55 } 56 57 func SetDeleteCallback(fn func(key string) bool) { 58 ite.SetDeleteCallback(fn) 59 } 60 61 // Deprecated: please use zcache.NewFast 62 // New new cache 63 func New(table string, accessCount ...bool) *Table { 64 mutex.Lock() 65 t, ok := cache[table] 66 67 if !ok { 68 t, ok = cache[table] 69 if !ok { 70 t = &Table{ 71 name: table, 72 items: make(map[string]*Item), 73 } 74 t.accessCount = zutil.NewBool(len(accessCount) > 0 && accessCount[0]) 75 cache[table] = t 76 } 77 } 78 79 mutex.Unlock() 80 return t 81 }