5 Star 0 Fork 0

Md/gu

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
manager.go 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
liyafei 提交于 2023-10-29 14:26 . 增加过期的map
package ttlmap
import (
"sync"
"time"
"gitee.com/MikeDDD/gu/guutil"
"gitee.com/MikeDDD/gu/logs"
)
type entity struct {
key string
value any
expireAt int64
}
type TtlMap struct {
lock *sync.RWMutex
entities map[string]*entity
}
func New() *TtlMap {
m := &TtlMap{
lock: new(sync.RWMutex),
entities: make(map[string]*entity),
}
guutil.GoWithRecover(func() {
for range time.NewTicker(time.Second).C {
m.recover()
}
})
return m
}
func (t *TtlMap) recover() {
defer guutil.InDeferRecover()
t.lock.Lock()
defer t.lock.Unlock()
for k, v := range t.entities {
if time.Now().UnixMilli() > v.expireAt {
logs.Debug("recover %v", k)
delete(t.entities, k)
}
}
}
func (t *TtlMap) Set(key string, value any, ttl time.Duration) {
t.lock.Lock()
defer t.lock.Unlock()
t.entities[key] = &entity{
key: key,
value: value,
expireAt: time.Now().UnixMilli() + ttl.Milliseconds(),
}
}
func (t *TtlMap) SetSpecific(key string, value any, expireAt int64) {
t.lock.Lock()
defer t.lock.Unlock()
t.entities[key] = &entity{
key: key,
value: value,
expireAt: expireAt,
}
}
func (t *TtlMap) Get(key string) any {
t.lock.RLock()
defer t.lock.RUnlock()
v, exists := t.entities[key]
if !exists {
return nil
}
if time.Now().UnixMilli() >= v.expireAt {
return nil
}
return v.value
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/MikeDDD/gu.git
git@gitee.com:MikeDDD/gu.git
MikeDDD
gu
gu
v0.0.126

搜索帮助