This commit is contained in:
Simon Ding
2024-08-07 11:20:21 +08:00
parent f48b3c657e
commit 1aa3dca2c6

24
pkg/cache/cache.go vendored
View File

@@ -4,35 +4,20 @@ import (
"polaris/log"
"polaris/pkg/utils"
"time"
"github.com/robfig/cron"
)
func NewCache[T comparable, S any](timeout time.Duration) *Cache[T, S] {
c := &Cache[T, S]{
m: utils.Map[T, inner[S]]{},
timeout: timeout,
cr: cron.New(),
}
c.cr.AddFunc("@ervery 1m", func() {
c.m.Range(func(key T, value inner[S]) bool {
if time.Since(value.t) > c.timeout {
log.Debugf("delete old cache: %v", key)
c.m.Delete(key)
}
return true
})
})
c.cr.Start()
return c
}
type Cache[T comparable, S any] struct {
m utils.Map[T, inner[S]]
timeout time.Duration
cr *cron.Cron
}
type inner[S any] struct {
@@ -45,6 +30,15 @@ func (c *Cache[T, S]) Set(key T, value S) {
}
func (c *Cache[T, S]) Get(key T) (S, bool) {
c.m.Range(func(key T, value inner[S]) bool {
if time.Since(value.t) > c.timeout {
log.Debugf("delete old cache: %v", key)
c.m.Delete(key)
}
return true
})
v, ok := c.m.Load(key)
if !ok {
return getZero[S](), ok