mirror of
https://github.com/simon-ding/polaris.git
synced 2026-02-06 15:10:49 +08:00
update
This commit is contained in:
24
pkg/cache/cache.go
vendored
24
pkg/cache/cache.go
vendored
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user