77 lines
1.3 KiB
Go
Raw Permalink Normal View History

2025-01-13 22:58:50 +08:00
package cache
import (
"sync"
"time"
)
// Cache any
type Cache interface {
Get(key string) any
Set(key string, val any, timeout time.Duration) error
IsExist(key string) bool
Delete(key string) error
}
// data 存储数据用的
type data struct {
Data any
Expired time.Time
}
// Memory 实现一个内存缓存
type Memory struct {
sync.Map
}
var m = sync.Map{}
// NewMemory 实例化一个内存缓存器
func NewMemory() Cache {
return &Memory{
sync.Map{},
}
}
// Get 获取缓存的值
func (mem *Memory) Get(key string) any {
if val, ok := mem.Load(key); ok {
val := val.(*data)
// 判断缓存是否过期
if val.Expired.Before(time.Now()) {
// 删除这个key
_ = mem.Delete(key)
return nil
}
return val.Data
}
return nil
}
// Set 设置一个值
func (mem *Memory) Set(key string, val any, timeout time.Duration) error {
mem.Store(key, &data{
Data: val,
Expired: time.Now().Add(timeout),
})
return nil
}
// IsExist 判断值是否存在
func (mem *Memory) IsExist(key string) bool {
if val, ok := mem.Load(key); ok {
val := val.(*data)
if val.Expired.Before(time.Now()) {
return false
}
return true
}
return false
}
// Delete 删除一个值
func (mem *Memory) Delete(key string) error {
return mem.Delete(key)
}