package cache import ( "github.com/hashicorp/golang-lru/v2/expirable" "github.com/mailru/easyjson" "time" ) type ttlCache struct { buf *expirable.LRU[string, []byte] } 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) bool { buf, ok := c.buf.Get(elm.Key()) if !ok { return false } if err := easyjson.Unmarshal(buf, elm); err != nil { return false } return true } func (c *ttlCache) Set(elm Element) bool { var k = elm.Key() buf, err := easyjson.Marshal(elm) if err != nil { c.buf.Remove(k) return false } c.buf.Add(k, buf) return true } func (c *ttlCache) String() string { return "ttl_lru_cache" } func (c *ttlCache) Close() error { if c.buf != nil { c.buf.Purge() } return nil }