Go-Cache 缓存包 - 高效的Golang 缓存解决方案

silverwq
2023-12-15 / 1 评论 / 108 阅读 / 正在检测是否收录...

第三方包github.com/patrickmn/go-cache

代码实现示例

package cache

import (
    gocache "github.com/patrickmn/go-cache"
    "strings"
    "sync"
    "time"
)

const (
    BaseKey = "platform-idstore"
)

var (
    once sync.Once
    instance *cache
)

var NewCache = New()

type Cache interface {
    Set(k string, v interface{}, d time.Duration)
    Get(k string) (interface{}, bool)
    Delete(k string)
    MatchDelete(matchKey string)
    Flush()
}

type cache struct {
    client gocache.Cache
}

func (c *cache) addBaseKey(k string) (key string) {
    return BaseKey + ":" + k
}

func (c *cache) Set(k string, v interface{}, d time.Duration) {
    key := c.addBaseKey(k)
    c.client.Set(key, v, d)
}

func (c *cache) Get(k string) (interface{}, bool) {
    key := c.addBaseKey(k)
    return c.client.Get(key)
}

func (c *cache) Delete(k string) {
    key := c.addBaseKey(k)
    c.client.Delete(key)
}

func (c *cache) MatchDelete(matchKey string) {
    keys := c.getMatchKeys(matchKey)
    for _, key := range keys {
        c.client.Delete(key)
    }
}

func (c *cache) getMatchKeys(match string) (keys []string){
    items := c.client.Items()
    for key, _ := range items {
        matchKey := c.addBaseKey(match)
        if strings.Index(key, matchKey) == 0 {
            keys = append(keys, key)
        }
    }
    return
}

func (c *cache) Flush() {
    items := c.client.Items()
    for key, _ := range items {
        if strings.Index(key, BaseKey) == 0 {
            c.Delete(strings.Replace(key, BaseKey + ":", "", 1))
        }
    }
}

func New() Cache {
    once.Do(func() {
        instance = &cache{
            client: *gocache.New(1*time.Hour, 6*time.Hour),
        }
    })
    return instance
}

0

评论 (1)

取消
  1. 头像
    silverwq 作者
    Windows 10 · Google Chrome

    啊啥的发

    回复