添加缓存
This commit is contained in:
@@ -12,11 +12,12 @@ import (
|
||||
// 到设定的点就删除
|
||||
|
||||
type cache struct {
|
||||
store sync.Map
|
||||
prefix string
|
||||
}
|
||||
|
||||
var one sync.Once
|
||||
var c *cache
|
||||
var store sync.Map
|
||||
|
||||
type cacheData struct {
|
||||
key string
|
||||
@@ -26,19 +27,22 @@ type cacheData struct {
|
||||
|
||||
var ErrorEmpty error = errors.New("empty cache")
|
||||
|
||||
func NewCache() *cache {
|
||||
func NewCache(prefix string) *cache {
|
||||
|
||||
c = &cache{
|
||||
prefix: prefix,
|
||||
}
|
||||
|
||||
one.Do(func() {
|
||||
c = &cache{}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
c.store.Range(func(key, value interface{}) bool {
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
if value.(*cacheData).expire.Before(time.Now()) {
|
||||
c.store.Delete(key)
|
||||
store.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
@@ -52,16 +56,18 @@ func (c *cache) Set(key string, value interface{}, expire time.Duration) {
|
||||
expire = time.Hour * 24 * 365
|
||||
}
|
||||
cd := &cacheData{key, value, time.Now().Add(expire)}
|
||||
c.store.Store(key, cd)
|
||||
key = c.prefix + key
|
||||
store.Store(key, cd)
|
||||
}
|
||||
|
||||
// 读取缓存
|
||||
func (c *cache) Get(key string) (interface{}, error) {
|
||||
if v, ok := c.store.Load(key); ok {
|
||||
key = c.prefix + key
|
||||
if v, ok := store.Load(key); ok {
|
||||
|
||||
cc := v.(*cacheData)
|
||||
if cc.expire.Before(time.Now()) {
|
||||
c.store.Delete(key)
|
||||
store.Delete(key)
|
||||
return nil, ErrorEmpty
|
||||
}
|
||||
return cc.data, nil
|
||||
@@ -71,5 +77,17 @@ func (c *cache) Get(key string) (interface{}, error) {
|
||||
|
||||
// 删除缓存
|
||||
func (c *cache) Delete(key string) {
|
||||
c.store.Delete(key)
|
||||
key = c.prefix + key
|
||||
store.Delete(key)
|
||||
}
|
||||
|
||||
// 清空缓存
|
||||
func (c *cache) Clear() {
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
// 根据前缀删除
|
||||
if key.(string)[:len(c.prefix)] == c.prefix {
|
||||
store.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
+3
-3
@@ -9,12 +9,12 @@ import (
|
||||
)
|
||||
|
||||
func TestCache(t *testing.T) {
|
||||
cachex.NewCache().Set("test", "test", time.Second*5)
|
||||
cachex.NewCache("").Set("test", "test", time.Second*5)
|
||||
|
||||
da, err := cachex.NewCache().Get("test")
|
||||
da, err := cachex.NewCache("").Get("test")
|
||||
fmt.Println(da, err)
|
||||
|
||||
time.Sleep(time.Second * 5)
|
||||
da, err = cachex.NewCache().Get("test")
|
||||
da, err = cachex.NewCache("").Get("test")
|
||||
fmt.Println(da, err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user