package kvcache import ( "time" "github.com/fanjindong/go-cache" ) const ( NoExpiration time.Duration = -1 ) type KVCache[V any] struct { c cache.ICache expiration time.Duration } func NewKVCache[V any]() *KVCache[V] { return NewExpireStore[V](NoExpiration) } func NewExpireStore[V any](defaultExpiration time.Duration, iopts ...cache.ICacheOption) *KVCache[V] { opts := []cache.ICacheOption{ cache.WithShards(16), cache.WithClearInterval(time.Minute), } opts = append(opts, iopts...) c := cache.NewMemCache(opts...) return &KVCache[V]{ c: c, expiration: defaultExpiration, } } func (s *KVCache[V]) Set(k string, v V) { if s.expiration == NoExpiration { s.c.Set(k, v) return } s.c.Set(k, v, cache.WithEx(s.expiration)) } func (s *KVCache[V]) SetEx(k string, v V, ex time.Duration) { s.c.Set(k, v, cache.WithEx(ex)) } func (s *KVCache[V]) Get(k string) (v V, ok bool) { val, ok := s.c.Get(k) if !ok { return } v = val.(V) return } func (s *KVCache[V]) Delete(keys ...string) { s.c.Del(keys...) } func (s *KVCache[V]) ForEach(f func(k string, v V)) { for k, v := range s.c.ToMap() { f(k, v.(V)) } } func (s *KVCache[V]) Count() int { return len(s.c.ToMap()) }