// Package cache ... // // Description : cache ... // // Author : go_developer@163.com<白茶清欢> // // Date : 2024-06-14 16:50 package cache import ( "context" "errors" cacheAbstract "git.zhangdeman.cn/zhangdeman/cache/abstract" gocache "github.com/patrickmn/go-cache" "sync" "time" ) var ( GocacheClient = &Gocache{} ) // Gocache 基于gocache的内存缓存 // // Author : go_developer@163.com<白茶清欢> // // Date : 16:51 2024/6/14 type Gocache struct{} func (g *Gocache) Exist(ctx context.Context, cacheInstanceFlag string, key string) (bool, error) { _, exist := GocacheStorageClient.Get(cacheInstanceFlag).Get(key) return exist, nil } func (g *Gocache) TTL(ctx context.Context, cacheInstanceFlag string, key string) (int64, error) { var ( exist bool expireAt time.Time ) _, expireAt, exist = GocacheStorageClient.Get(cacheInstanceFlag).GetWithExpiration(key) if !exist { // 和redis key不存在返回值一致 return -2, nil } if expireAt.Unix() == 0 { // 存在并且未设置过期时间, 和redis key返回值一致 return -1, nil } return expireAt.Unix() - time.Now().Unix(), nil } func (g *Gocache) Set(ctx context.Context, cacheInstanceFlag string, key string, value string, ttl int64) error { now := time.Now() if now.Unix() < ttl { ttl = ttl - now.Unix() } GocacheStorageClient.Get(cacheInstanceFlag).Set(key, value, time.Duration(ttl)*time.Second) return nil } func (g *Gocache) Get(ctx context.Context, cacheInstanceFlag string, key string) (string, error) { val, exist := GocacheStorageClient.Get(cacheInstanceFlag).Get(key) if !exist { return "", errors.New(key + " : not found") } return val.(string), nil } func (g *Gocache) GetWithParse(ctx context.Context, cacheInstanceFlag string, key string, parseFunc cacheAbstract.ResultParseFunc) (string, error) { val, err := g.Get(ctx, cacheInstanceFlag, key) if nil != err { return "", err } if nil == parseFunc { return val, nil } return val, parseFunc(val) } func (g *Gocache) Delete(ctx context.Context, cacheInstanceFlag string, key string) error { GocacheStorageClient.Get(cacheInstanceFlag).Delete(key) return nil } var GocacheStorageClient = &GocacheStorage{ lock: &sync.RWMutex{}, clientTable: make(map[string]*gocache.Cache), } type GocacheStorage struct { lock *sync.RWMutex clientTable map[string]*gocache.Cache } func (g *GocacheStorage) Add(cacheInstanceFlag string) { _ = g.Get(cacheInstanceFlag) } func (g *GocacheStorage) Del(cacheInstanceFlag string) { g.lock.Lock() defer g.lock.Unlock() delete(g.clientTable, cacheInstanceFlag) } func (g *GocacheStorage) Get(cacheInstanceFlag string) *gocache.Cache { g.lock.Lock() defer g.lock.Unlock() if _, exist := g.clientTable[cacheInstanceFlag]; !exist { g.clientTable[cacheInstanceFlag] = gocache.New(0, 0) } return g.clientTable[cacheInstanceFlag] }