get添加错误码

This commit is contained in:
yun
2023-12-29 16:22:07 +08:00
parent f52d18c16b
commit f1778c39c5
+14 -7
View File
@@ -1,6 +1,7 @@
package cachex
import (
"errors"
"sync"
"time"
)
@@ -13,8 +14,9 @@ import (
type cache struct {
store sync.Map
}
var one sync.Once
var c cache
var c *cache
type cacheData struct {
key string
@@ -22,9 +24,11 @@ type cacheData struct {
expire time.Time
}
var ErrorEmpty error = errors.New("empty cache")
func NewCache() *cache {
one.Do(func() {
c = cache{}
c = &cache{}
go func() {
for {
@@ -39,27 +43,30 @@ func NewCache() *cache {
}
}()
})
return &c
return c
}
// 设置缓存
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
if expire == 0 {
expire = time.Hour * 24 * 365
}
cd := &cacheData{key, value, time.Now().Add(expire)}
c.store.Store(key, cd)
}
// 读取缓存
func (c *cache) Get(key string) interface{} {
func (c *cache) Get(key string) (interface{}, error) {
if v, ok := c.store.Load(key); ok {
cc := v.(*cacheData)
if cc.expire.Before(time.Now()) {
c.store.Delete(key)
return nil
return nil, ErrorEmpty
}
return cc.data
return cc.data, nil
}
return nil
return nil, ErrorEmpty
}
// 删除缓存