Files

69 lines
1.0 KiB
Go
Raw Permalink Normal View History

2023-09-16 20:14:20 +08:00
package cachex
import (
"sync"
"time"
)
2023-11-10 00:05:27 +08:00
// 应用内缓存
// 特点
// 1.全局单实例
2023-09-16 20:14:20 +08:00
// 到设定的点就删除
2023-11-10 00:05:27 +08:00
type cache struct{
store sync.Map
}
var one sync.Once
var c cache
2023-09-16 20:14:20 +08:00
type cacheData struct {
key string
data interface{}
expire time.Time
}
func NewCache() *cache {
2023-11-10 00:05:27 +08:00
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
2023-09-16 20:14:20 +08:00
}
2023-11-10 00:05:27 +08:00
// 设置缓存
2023-09-16 20:14:20 +08:00
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
2023-11-10 00:05:27 +08:00
cd := &cacheData{key, value, time.Now().Add(expire)}
c.store.Store(key, cd)
2023-09-16 20:14:20 +08:00
}
2023-11-10 00:05:27 +08:00
// 读取缓存
2023-09-16 20:14:20 +08:00
func (c *cache) Get(key string) interface{} {
2023-11-10 00:05:27 +08:00
if v, ok := c.store.Load(key); ok {
2023-09-16 20:14:20 +08:00
cc := v.(*cacheData)
if cc.expire.Before(time.Now()) {
2023-11-10 00:05:27 +08:00
c.store.Delete(key)
2023-09-16 20:14:20 +08:00
return nil
}
return cc.data
}
return nil
}
2023-11-10 00:05:27 +08:00
// 删除缓存
2023-09-16 20:14:20 +08:00
func (c *cache) Delete(key string) {
2023-11-10 00:05:27 +08:00
c.store.Delete(key)
2023-09-16 20:14:20 +08:00
}