This commit is contained in:
2025-02-21 08:42:56 +08:00
parent a0ee3b858b
commit 2f99149d92
9 changed files with 146 additions and 124 deletions

View File

@@ -9,7 +9,7 @@ import (
type Cache[K comparable, V any] struct {
mu sync.RWMutex
data map[K]*Data[V] // 数据
data sync.Map // 数据
cSet func(K, Data[V]) // 设置数据回调
cGet func(K, Data[V]) // 获取数据回调
cGetData func(K, Data[V]) // 获取数据内容回调
@@ -33,7 +33,7 @@ type Data[V any] struct {
func NewCache[K comparable, V any]() *Cache[K, V] {
defFunc := func(k K, d Data[V]) {}
c := &Cache[K, V]{
data: make(map[K]*Data[V]),
data: sync.Map{},
cSet: defFunc,
cGet: defFunc,
cGetData: defFunc,
@@ -60,27 +60,14 @@ func (c *Cache[K, V]) collection() func() {
return
case <-ticker.C:
now := time.Now()
var dKeys []K
c.mu.RLock()
for k, v := range c.data {
if v.End.IsZero() && v.End.Before(now) {
dKeys = append(dKeys, k)
}
}
c.mu.RUnlock()
// 删除过期数据
if len(dKeys) > 0 {
c.mu.Lock()
for _, k := range dKeys {
if c.cDel != nil {
c.cDel(k, *c.data[k])
c.data.Range(func(key, value any) bool {
if v, ok := value.(*Data[V]); ok {
if !v.End.IsZero() && v.End.Before(now) {
c.data.Delete(key)
}
delete(c.data, k)
}
c.mu.Unlock()
}
return true
})
}
}
}()
@@ -104,5 +91,6 @@ func (c *Cache[K, V]) Destroy() {
if c.persist != nil {
c.persist()
}
c.data.Clear()
return
}