gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/myx/cachex/cache.go (about) 1 package cachex 2 3 import ( 4 "context" 5 "sync" 6 "time" 7 ) 8 9 type ICache interface { 10 Set(key string, val interface{}) 11 Delete(key string) 12 Expire(key string, duration time.Duration, handler func(key string, data interface{})) 13 Get(key string) (val interface{}, ok bool) 14 Dispose() 15 } 16 17 var ( 18 cacheGlobal *Cache 19 ) 20 21 func NewCacheSyncNoExpire() *Cache { 22 c := &Cache{ 23 data: &sync.Map{}, 24 expiredSpace: time.Second * 5, 25 expiredSet: map[string]*expiredItem{}, 26 } 27 return c 28 } 29 30 func NewCache() *Cache { 31 c := &Cache{ 32 data: &sync.Map{}, 33 expiredSpace: time.Second * 5, 34 expiredSet: map[string]*expiredItem{}, 35 } 36 c.goCleanExpireList() 37 return c 38 } 39 40 type Cache struct { 41 // 缓存数据库中获取的数据 42 data *sync.Map 43 // 44 mu sync.RWMutex 45 // 46 expiredSet map[string]*expiredItem 47 // 48 expiredRoot *expiredItem 49 // 过期检查间隔 50 expiredSpace time.Duration 51 } 52 53 func (c *Cache) Dispose() { 54 c.data = nil 55 } 56 57 func (c *Cache) Set(key string, val interface{}) { 58 c.data.Store(key, val) 59 } 60 61 func (c *Cache) Delete(key string) { 62 c.data.Delete(key) 63 } 64 65 func (c *Cache) Get(key string) (val interface{}, ok bool) { 66 return c.data.Load(key) 67 } 68 69 // 从cache中获取对象, 如果存在, 通过has方法进行处理; 如果不存在, 通过create方法创建, 接着调用has方法 70 // 该方法没有返回值 71 func (c *Cache) GetOrNew(key string, has func(ival interface{}), create func() interface{}) interface{} { 72 ival, ok := c.Get(key) 73 if ok == false { 74 ival = create() 75 if ival == nil { 76 return nil 77 } 78 c.Set(key, ival) 79 } 80 has(ival) 81 return ival 82 } 83 84 func NewContext(ctx context.Context) *Context { 85 return &Context{ 86 Context: ctx, 87 } 88 } 89 90 type Context struct { 91 context.Context 92 93 // 94 cache *Cache 95 } 96 97 func (ctx *Context) GetCacheGlobal() *Cache { 98 if cacheGlobal == nil { 99 cacheGlobal = NewCache() 100 } 101 return cacheGlobal 102 } 103 104 func (ctx *Context) GetCache() *Cache { 105 if ctx.cache == nil { 106 ctx.cache = NewCache() 107 } 108 return ctx.cache 109 }