Files
cachex/cachex.go
T

89 lines
1.4 KiB
Go
Raw Normal View History

2023-11-24 22:28:22 +08:00
package cachex
import (
2023-12-29 16:22:07 +08:00
"errors"
2023-11-24 22:28:22 +08:00
"sync"
"time"
)
// 应用内缓存
// 特点
// 1.全局单实例
// 到设定的点就删除
2023-12-29 16:22:07 +08:00
type cache struct {
2024-03-17 16:14:25 +08:00
prefix string
2024-04-12 16:29:15 +08:00
store sync.Map
2023-11-24 22:28:22 +08:00
}
2023-12-29 16:22:07 +08:00
2023-11-24 22:28:22 +08:00
type cacheData struct {
key string
data interface{}
expire time.Time
}
2023-12-29 16:22:07 +08:00
var ErrorEmpty error = errors.New("empty cache")
2024-03-17 16:14:25 +08:00
func NewCache(prefix string) *cache {
2024-04-12 16:29:15 +08:00
c := &cache{
2024-03-17 16:14:25 +08:00
prefix: prefix,
}
2024-04-12 16:29:15 +08:00
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)
}
}()
2023-11-24 22:28:22 +08:00
2023-12-29 16:22:07 +08:00
return c
2023-11-24 22:28:22 +08:00
}
// 设置缓存
func (c *cache) Set(key string, value interface{}, expire time.Duration) {
2023-12-29 16:22:07 +08:00
if expire == 0 {
expire = time.Hour * 24 * 365
}
2023-11-24 22:28:22 +08:00
cd := &cacheData{key, value, time.Now().Add(expire)}
2024-03-17 16:14:25 +08:00
key = c.prefix + key
2024-04-12 16:29:15 +08:00
c.store.Store(key, cd)
2023-11-24 22:28:22 +08:00
}
// 读取缓存
2023-12-29 16:22:07 +08:00
func (c *cache) Get(key string) (interface{}, error) {
2024-03-17 16:14:25 +08:00
key = c.prefix + key
2024-04-12 16:29:15 +08:00
if v, ok := c.store.Load(key); ok {
2023-11-24 22:28:22 +08:00
cc := v.(*cacheData)
if cc.expire.Before(time.Now()) {
2024-04-12 16:29:15 +08:00
c.store.Delete(key)
2023-12-29 16:22:07 +08:00
return nil, ErrorEmpty
2023-11-24 22:28:22 +08:00
}
2023-12-29 16:22:07 +08:00
return cc.data, nil
2023-11-24 22:28:22 +08:00
}
2023-12-29 16:22:07 +08:00
return nil, ErrorEmpty
2023-11-24 22:28:22 +08:00
}
// 删除缓存
func (c *cache) Delete(key string) {
2024-03-17 16:14:25 +08:00
key = c.prefix + key
2024-04-12 16:29:15 +08:00
c.store.Delete(key)
2024-03-17 16:14:25 +08:00
}
// 清空缓存
func (c *cache) Clear() {
2024-04-12 16:29:15 +08:00
c.store.Range(func(key, value interface{}) bool {
2024-03-17 16:14:25 +08:00
// 根据前缀删除
if key.(string)[:len(c.prefix)] == c.prefix {
2024-04-12 16:29:15 +08:00
c.store.Delete(key)
2024-03-17 16:14:25 +08:00
}
return true
})
2023-11-24 22:28:22 +08:00
}