mihomo/common/cache/cache.go

107 lines
1.8 KiB
Go
Raw Normal View History

2018-12-05 21:13:29 +08:00
package cache
import (
"runtime"
"sync"
"time"
)
// Cache store element with a expired time
type Cache struct {
*cache
}
type cache struct {
mapping sync.Map
janitor *janitor
}
type element struct {
Expired time.Time
2022-03-16 12:10:13 +08:00
Payload any
2018-12-05 21:13:29 +08:00
}
// Put element in Cache with its ttl
2022-03-16 12:10:13 +08:00
func (c *cache) Put(key any, payload any, ttl time.Duration) {
2018-12-05 21:13:29 +08:00
c.mapping.Store(key, &element{
Payload: payload,
Expired: time.Now().Add(ttl),
})
}
// Get element in Cache, and drop when it expired
2022-03-16 12:10:13 +08:00
func (c *cache) Get(key any) any {
2018-12-05 21:13:29 +08:00
item, exist := c.mapping.Load(key)
if !exist {
return nil
}
elm := item.(*element)
// expired
if time.Since(elm.Expired) > 0 {
c.mapping.Delete(key)
return nil
}
return elm.Payload
}
// GetWithExpire element in Cache with Expire Time
2022-03-16 12:10:13 +08:00
func (c *cache) GetWithExpire(key any) (payload any, expired time.Time) {
item, exist := c.mapping.Load(key)
if !exist {
return
}
elm := item.(*element)
// expired
if time.Since(elm.Expired) > 0 {
c.mapping.Delete(key)
return
}
return elm.Payload, elm.Expired
}
2018-12-05 21:13:29 +08:00
func (c *cache) cleanup() {
2022-03-16 12:10:13 +08:00
c.mapping.Range(func(k, v any) bool {
2018-12-05 21:13:29 +08:00
key := k.(string)
elm := v.(*element)
if time.Since(elm.Expired) > 0 {
c.mapping.Delete(key)
}
return true
})
}
type janitor struct {
interval time.Duration
stop chan struct{}
}
func (j *janitor) process(c *cache) {
ticker := time.NewTicker(j.interval)
for {
select {
case <-ticker.C:
c.cleanup()
case <-j.stop:
ticker.Stop()
return
}
}
}
func stopJanitor(c *Cache) {
c.janitor.stop <- struct{}{}
}
// New return *Cache
func New(interval time.Duration) *Cache {
j := &janitor{
interval: interval,
stop: make(chan struct{}),
}
c := &cache{janitor: j}
go j.process(c)
C := &Cache{c}
runtime.SetFinalizer(C, stopJanitor)
return C
}