优化部分

This commit is contained in:
Yun
2023-11-10 00:05:27 +08:00
parent b58d50778d
commit 3545414ef2
12 changed files with 166 additions and 647 deletions
+33 -24
View File
@@ -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)
}