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/log"
|
||||||
"polaris/pkg/utils"
|
"polaris/pkg/utils"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/robfig/cron"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewCache[T comparable, S any](timeout time.Duration) *Cache[T, S] {
|
func NewCache[T comparable, S any](timeout time.Duration) *Cache[T, S] {
|
||||||
c := &Cache[T, S]{
|
c := &Cache[T, S]{
|
||||||
m: utils.Map[T, inner[S]]{},
|
m: utils.Map[T, inner[S]]{},
|
||||||
timeout: timeout,
|
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
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
type Cache[T comparable, S any] struct {
|
type Cache[T comparable, S any] struct {
|
||||||
m utils.Map[T, inner[S]]
|
m utils.Map[T, inner[S]]
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
cr *cron.Cron
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type inner[S any] struct {
|
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) {
|
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)
|
v, ok := c.m.Load(key)
|
||||||
if !ok {
|
if !ok {
|
||||||
return getZero[S](), ok
|
return getZero[S](), ok
|
||||||
|
|||||||
Reference in New Issue
Block a user