60 lines
890 B
Go
60 lines
890 B
Go
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|