github.com/gogf/gf@v1.16.9/os/gcache/gcache_cache.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gcache 8 9 import ( 10 "context" 11 "github.com/gogf/gf/container/gvar" 12 "github.com/gogf/gf/os/gtimer" 13 "github.com/gogf/gf/util/gconv" 14 "time" 15 ) 16 17 // Cache struct. 18 type Cache struct { 19 adapter Adapter // Adapter for cache features. 20 ctx context.Context // Context for operations. 21 } 22 23 // New creates and returns a new cache object using default memory adapter. 24 // Note that the LRU feature is only available using memory adapter. 25 func New(lruCap ...int) *Cache { 26 memAdapter := newAdapterMemory(lruCap...) 27 c := &Cache{ 28 adapter: memAdapter, 29 } 30 // Here may be a "timer leak" if adapter is manually changed from memory adapter. 31 // Do not worry about this, as adapter is less changed and it dose nothing if it's not used. 32 gtimer.AddSingleton(time.Second, memAdapter.syncEventAndClearExpired) 33 return c 34 } 35 36 // Clone returns a shallow copy of current object. 37 func (c *Cache) Clone() *Cache { 38 return &Cache{ 39 adapter: c.adapter, 40 ctx: c.ctx, 41 } 42 } 43 44 // Ctx is a chaining function, which shallowly clones current object and sets the context 45 // for next operation. 46 func (c *Cache) Ctx(ctx context.Context) *Cache { 47 newCache := c.Clone() 48 newCache.ctx = ctx 49 return newCache 50 } 51 52 // SetAdapter changes the adapter for this cache. 53 // Be very note that, this setting function is not concurrent-safe, which means you should not call 54 // this setting function concurrently in multiple goroutines. 55 func (c *Cache) SetAdapter(adapter Adapter) { 56 c.adapter = adapter 57 } 58 59 // GetVar retrieves and returns the value of `key` as gvar.Var. 60 func (c *Cache) GetVar(key interface{}) (*gvar.Var, error) { 61 v, err := c.Get(key) 62 return gvar.New(v), err 63 } 64 65 // Removes deletes `keys` in the cache. 66 // Deprecated, use Remove instead. 67 func (c *Cache) Removes(keys []interface{}) error { 68 _, err := c.Remove(keys...) 69 return err 70 } 71 72 // KeyStrings returns all keys in the cache as string slice. 73 func (c *Cache) KeyStrings() ([]string, error) { 74 keys, err := c.Keys() 75 if err != nil { 76 return nil, err 77 } 78 return gconv.Strings(keys), nil 79 } 80 81 // KeyStrings returns all keys in the cache as string slice. 82 func (c *Cache) getCtx() context.Context { 83 if c.ctx == nil { 84 return context.Background() 85 } 86 return c.ctx 87 }