封装的方法类
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package cachex
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 内存缓存
|
||||
// 到设定的点就删除
|
||||
|
||||
var store sync.Map
|
||||
|
||||
type cache struct {}
|
||||
|
||||
type cacheData struct {
|
||||
key string
|
||||
data interface{}
|
||||
expire time.Time
|
||||
}
|
||||
|
||||
func NewCache() *cache {
|
||||
return &cache{}
|
||||
}
|
||||
|
||||
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
|
||||
cd := &cacheData{key,value,time.Now().Add(expire)}
|
||||
store.Store(key, cd)
|
||||
}
|
||||
|
||||
func (c *cache) Get(key string) interface{} {
|
||||
if v, ok := store.Load(key); ok {
|
||||
|
||||
cc := v.(*cacheData)
|
||||
if cc.expire.Before(time.Now()) {
|
||||
store.Delete(key)
|
||||
return nil
|
||||
}
|
||||
return cc.data
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user