package cache import ( "fmt" "gitea.codecodify.com/golang/tool/helper" "github.com/patrickmn/go-cache" "io/fs" "log" "os" "time" ) func init() { } const EmptyName = "" const cacheDir = "./cacheTemp" // location 使用cache2go实现本地缓存 type location struct { Name string c *cache.Cache } func NewLocation(name string) *location { return &location{ Name: name, c: getCache(), } } func (l location) Add(key string, val any, d time.Duration) bool { if has := l.Has(key); has == true { return false } l.Put(key, val, d) return true } func (l location) Has(key string) bool { _, found := l.get(key) return found } func (l location) Put(key string, val any, d time.Duration) { l.c.Set(key, val, d) _ = l.saveFile() } func (l location) Get(key string, defaultValue any) any { if v, err := l.get(key); err { return v } else { return defaultValue } } func (l location) Forever(key string, val any) { l.Put(key, val, cache.NoExpiration) } func (l location) get(key string) (any, bool) { _ = l.loadFile() return l.c.Get(key) } func getCache() *cache.Cache { return cache.New(2*time.Hour, 24*time.Hour) } func getFile(name string) string { name = helper.Ternary(len(name) > 0, name+".cache", "cache.cache").(string) _, err := os.Stat(cacheDir) if os.IsNotExist(err) { if err = os.Mkdir(cacheDir, fs.ModePerm); err != nil { log.Printf("【go-cache 创建缓存文件夹失败】error: %v", err) } } else if err != nil { log.Printf("【go-cache 创建缓存文件夹失败】error: %v", err) } return fmt.Sprintf("%s/%s", cacheDir, name) } func (l location) saveFile() error { if err := l.c.SaveFile(getFile(l.Name)); err != nil { log.Printf("【go-cache 设置缓存文件失败】error: %v", err) return err } return nil } func (l location) loadFile() error { if err := l.c.LoadFile(getFile(l.Name)); err != nil { log.Printf("【go-cache 加载缓存文件失败】error: %v", err) return err } return nil }