优化部分
This commit is contained in:
+33
-24
@@ -5,12 +5,16 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// 内存缓存
|
||||
// 应用内缓存
|
||||
// 特点
|
||||
// 1.全局单实例
|
||||
// 到设定的点就删除
|
||||
|
||||
var store sync.Map
|
||||
|
||||
type cache struct {}
|
||||
type cache struct{
|
||||
store sync.Map
|
||||
}
|
||||
var one sync.Once
|
||||
var c cache
|
||||
|
||||
type cacheData struct {
|
||||
key string
|
||||
@@ -19,20 +23,38 @@ type cacheData struct {
|
||||
}
|
||||
|
||||
func NewCache() *cache {
|
||||
return &cache{}
|
||||
one.Do(func() {
|
||||
c = cache{}
|
||||
|
||||
go func(){
|
||||
for {
|
||||
c.store.Range(func(key, value interface{}) bool {
|
||||
if value.(*cacheData).expire.Before(time.Now()) {
|
||||
c.store.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
})
|
||||
return &c
|
||||
}
|
||||
|
||||
// 设置缓存
|
||||
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
|
||||
cd := &cacheData{key,value,time.Now().Add(expire)}
|
||||
store.Store(key, cd)
|
||||
cd := &cacheData{key, value, time.Now().Add(expire)}
|
||||
c.store.Store(key, cd)
|
||||
}
|
||||
|
||||
// 读取缓存
|
||||
func (c *cache) Get(key string) interface{} {
|
||||
if v, ok := store.Load(key); ok {
|
||||
if v, ok := c.store.Load(key); ok {
|
||||
|
||||
cc := v.(*cacheData)
|
||||
if cc.expire.Before(time.Now()) {
|
||||
store.Delete(key)
|
||||
c.store.Delete(key)
|
||||
return nil
|
||||
}
|
||||
return cc.data
|
||||
@@ -40,20 +62,7 @@ func (c *cache) Get(key string) interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 删除缓存
|
||||
func (c *cache) Delete(key string) {
|
||||
store.Delete(key)
|
||||
}
|
||||
|
||||
func init() {
|
||||
for {
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
if value.(*cacheData).expire.Before(time.Now()) {
|
||||
store.Delete(key)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
|
||||
c.store.Delete(key)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package cachex_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"code.yun.ink/open/utils/cachex"
|
||||
)
|
||||
|
||||
func TestCache(t *testing.T) {
|
||||
cachex.NewCache().Set("test", "test", time.Second*5)
|
||||
|
||||
da := cachex.NewCache().Get("test")
|
||||
fmt.Println(da)
|
||||
|
||||
time.Sleep(time.Second *5)
|
||||
da = cachex.NewCache().Get("test")
|
||||
fmt.Println(da)
|
||||
}
|
||||
Reference in New Issue
Block a user