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(elm Element) error { var k = elm.Key() buf, err := elm.Marshal() if err != nil { c.buf.Remove(k) return err } c.buf.Add(k, 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 }