Feat: sync cache set expiraton

pull/21/head
zijiren233 2 years ago
parent 62a7e8f255
commit 2111d3bc31

@ -62,20 +62,28 @@ func (sc *SyncCache[K, V]) Load(key K) (value V, loaded bool) {
} }
func (sc *SyncCache[K, V]) LoadOrStore(key K, value V, expire time.Duration) (actual V, loaded bool) { func (sc *SyncCache[K, V]) LoadOrStore(key K, value V, expire time.Duration) (actual V, loaded bool) {
e, loaded := sc.cache.LoadOrStore(key, &entry[V]{ e, loaded := sc.cache.LoadOrStore(key, NewEntry[V](value, expire))
expiration: time.Now().Add(expire),
value: value,
})
if e.IsExpired() { if e.IsExpired() {
sc.cache.Store(key, &entry[V]{ sc.cache.Store(key, NewEntry[V](value, expire))
expiration: time.Now().Add(expire),
value: value,
})
return value, false return value, false
} }
return e.value, loaded return e.value, loaded
} }
func (sc *SyncCache[K, V]) AddExpiration(key K, d time.Duration) {
e, ok := sc.cache.Load(key)
if ok {
e.AddExpiration(d)
}
}
func (sc *SyncCache[K, V]) SetExpiration(key K, t time.Time) {
e, ok := sc.cache.Load(key)
if ok {
e.SetExpiration(t)
}
}
func (sc *SyncCache[K, V]) Delete(key K) { func (sc *SyncCache[K, V]) Delete(key K) {
sc.LoadAndDelete(key) sc.LoadAndDelete(key)
} }

@ -1,12 +1,30 @@
package synccache package synccache
import "time" import (
"sync/atomic"
"time"
)
type entry[V any] struct { type entry[V any] struct {
expiration time.Time expiration int64
value V value V
} }
func NewEntry[V any](value V, expire time.Duration) *entry[V] {
return &entry[V]{
expiration: time.Now().Add(expire).UnixMilli(),
value: value,
}
}
func (e *entry[V]) IsExpired() bool { func (e *entry[V]) IsExpired() bool {
return time.Now().After(e.expiration) return time.Now().After(time.UnixMilli(atomic.LoadInt64(&e.expiration)))
}
func (e *entry[V]) AddExpiration(d time.Duration) {
atomic.AddInt64(&e.expiration, int64(d))
}
func (e *entry[V]) SetExpiration(t time.Time) {
atomic.StoreInt64(&e.expiration, t.UnixMilli())
} }

Loading…
Cancel
Save