wp-go/cache/memorymapcache.go

111 lines
2.1 KiB
Go
Raw Normal View History

2023-02-02 11:16:18 +00:00
package cache
import (
"context"
2023-11-28 14:46:22 +00:00
"github.com/fthvgb1/wp-go/helper"
2023-02-02 11:16:18 +00:00
"github.com/fthvgb1/wp-go/safety"
"time"
)
type MemoryMapCache[K comparable, V any] struct {
*safety.Map[K, mapVal[V]]
expireTime func() time.Duration
2023-02-02 11:16:18 +00:00
}
func NewMemoryMapCache[K comparable, V any](expireTime func() time.Duration) *MemoryMapCache[K, V] {
return &MemoryMapCache[K, V]{
Map: safety.NewMap[K, mapVal[V]](),
expireTime: expireTime,
}
2023-02-02 11:16:18 +00:00
}
type mapVal[T any] struct {
setTime time.Time
ver int
data T
}
2023-11-02 14:40:13 +00:00
func (m *MemoryMapCache[K, V]) SetExpiredTime(f func() time.Duration) {
m.expireTime = f
}
func (m *MemoryMapCache[K, V]) GetExpireTime(_ context.Context) time.Duration {
return m.expireTime()
}
2023-02-02 11:16:18 +00:00
func (m *MemoryMapCache[K, V]) Get(_ context.Context, key K) (r V, ok bool) {
v, ok := m.Load(key)
if !ok {
return
}
r = v.data
t := m.expireTime() - time.Now().Sub(v.setTime)
if t <= 0 {
ok = false
2023-02-02 11:16:18 +00:00
}
return
}
func (m *MemoryMapCache[K, V]) Set(_ context.Context, key K, val V) {
2023-02-02 11:16:18 +00:00
v, ok := m.Load(key)
t := time.Now()
if ok {
v.data = val
v.setTime = t
v.ver++
} else {
v = mapVal[V]{
setTime: t,
ver: 1,
data: val,
}
}
m.Store(key, v)
}
func (m *MemoryMapCache[K, V]) Ttl(_ context.Context, key K) time.Duration {
2023-02-02 11:16:18 +00:00
v, ok := m.Load(key)
if !ok {
2023-02-02 14:56:09 +00:00
return time.Duration(-1)
2023-02-02 11:16:18 +00:00
}
return m.expireTime() - time.Now().Sub(v.setTime)
2023-02-02 11:16:18 +00:00
}
func (m *MemoryMapCache[K, V]) Ver(_ context.Context, key K) int {
v, ok := m.Load(key)
if !ok {
return -1
}
return v.ver
}
func (m *MemoryMapCache[K, V]) Flush(context.Context) {
2023-02-03 14:43:20 +00:00
m.Map.Flush()
2023-02-02 11:16:18 +00:00
}
func (m *MemoryMapCache[K, V]) Del(_ context.Context, keys ...K) {
for _, key := range keys {
m.Map.Delete(key)
}
2023-02-02 11:16:18 +00:00
}
func (m *MemoryMapCache[K, V]) ClearExpired(_ context.Context) {
2023-02-02 11:16:18 +00:00
now := time.Duration(time.Now().UnixNano())
m.Range(func(k K, v mapVal[V]) bool {
if now > time.Duration(v.setTime.UnixNano())+m.expireTime() {
2023-02-02 11:16:18 +00:00
m.Map.Delete(k)
}
return true
})
}
2023-11-28 14:46:22 +00:00
func (m *MemoryMapCache[K, V]) Refresh(_ context.Context, k K, a ...any) {
v, ok := m.Load(k)
if !ok {
return
}
t := helper.ParseArgs(time.Now(), a...)
v.setTime = t
m.Store(k, v)
}