Add freelru.GetWithLifetimeNoExpire

This commit is contained in:
世界 2025-02-24 18:25:10 +08:00
parent ea0ac932ae
commit ea82ac275f
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
4 changed files with 41 additions and 0 deletions

View file

@ -49,6 +49,8 @@ type Cache[K comparable, V comparable] interface {
GetWithLifetime(key K) (V, time.Time, bool)
GetWithLifetimeNoExpire(key K) (V, time.Time, bool)
// GetAndRefresh returns the value associated with the key, setting it as the most
// recently used item.
// The lifetime of the found cache item is refreshed, even if it was already expired.

View file

@ -500,6 +500,24 @@ func (lru *LRU[K, V]) getWithLifetime(hash uint32, key K) (value V, lifetime tim
return
}
func (lru *LRU[K, V]) GetWithLifetimeNoExpire(key K) (value V, lifetime time.Time, ok bool) {
return lru.getWithLifetimeNoExpire(lru.hash(key), key)
}
func (lru *LRU[K, V]) getWithLifetimeNoExpire(hash uint32, key K) (value V, lifetime time.Time, ok bool) {
if pos, ok := lru.findKeyNoExpire(hash, key); ok {
if pos != lru.head {
lru.unlinkElement(pos)
lru.setHead(pos)
}
lru.metrics.Hits++
return lru.elements[pos].value, time.UnixMilli(lru.elements[pos].expire), ok
}
lru.metrics.Misses++
return
}
// GetAndRefresh returns the value associated with the key, setting it as the most
// recently used item.
// The lifetime of the found cache item is refreshed, even if it was already expired.

View file

@ -187,6 +187,17 @@ func (lru *ShardedLRU[K, V]) GetWithLifetime(key K) (value V, lifetime time.Time
return
}
func (lru *ShardedLRU[K, V]) GetWithLifetimeNoExpire(key K) (value V, lifetime time.Time, ok bool) {
hash := lru.hash(key)
shard := (hash >> 16) & lru.mask
lru.mus[shard].RLock()
value, lifetime, ok = lru.lrus[shard].getWithLifetimeNoExpire(hash, key)
lru.mus[shard].RUnlock()
return
}
// GetAndRefresh returns the value associated with the key, setting it as the most
// recently used item.
// The lifetime of the found cache item is refreshed, even if it was already expired.

View file

@ -108,6 +108,16 @@ func (lru *SyncedLRU[K, V]) GetWithLifetime(key K) (value V, lifetime time.Time,
return
}
func (lru *SyncedLRU[K, V]) GetWithLifetimeNoExpire(key K) (value V, lifetime time.Time, ok bool) {
hash := lru.lru.hash(key)
lru.mu.Lock()
value, lifetime, ok = lru.lru.getWithLifetimeNoExpire(hash, key)
lru.mu.Unlock()
return
}
// GetAndRefresh returns the value associated with the key, setting it as the most
// recently used item.
// The lifetime of the found cache item is refreshed, even if it was already expired.