package cache import ( "github.com/hashicorp/golang-lru/v2/expirable" "time" ) type ttlCache struct { buf *expirable.LRU[string, []byte] } //goland:noinspection GoUnusedExportedFunction func NewTTLCache(size int, ttl time.Duration) Cache { c := &ttlCache{} c.buf = expirable.NewLRU[string, []byte](size, nil, ttl) return c } func (c *ttlCache) Get(elm Element) error { var k = elm.Key() buf, ok := c.buf.Get(k) if !ok { return ErrorNotFound } if err := elm.Unmarshal(buf); err != nil { c.buf.Remove(k) return err } return nil } func (c *ttlCache) Set(items ...Element) error { if items == nil { return nil } for _, item := range items { if item == nil { continue } buf, err := item.Marshal() if err != nil { return err } c.buf.Add(item.Key(), buf) } return nil } func (c *ttlCache) String() string { return "ttl_lru_cache" } func (c *ttlCache) Close() error { if c.buf != nil { c.buf.Purge() } return nil }