ttl_cache.go 843 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package cache
  2. import (
  3. "github.com/hashicorp/golang-lru/v2/expirable"
  4. "github.com/mailru/easyjson"
  5. "time"
  6. )
  7. type ttlCache struct {
  8. buf *expirable.LRU[string, []byte]
  9. }
  10. func New(size int, ttl time.Duration) Cache {
  11. c := &ttlCache{}
  12. c.buf = expirable.NewLRU[string, []byte](size, nil, ttl)
  13. return c
  14. }
  15. func (c *ttlCache) Get(elm Element) bool {
  16. buf, ok := c.buf.Get(elm.Key())
  17. if !ok {
  18. return false
  19. }
  20. if err := easyjson.Unmarshal(buf, elm); err != nil {
  21. return false
  22. }
  23. return true
  24. }
  25. func (c *ttlCache) Set(elm Element) bool {
  26. var k = elm.Key()
  27. buf, err := easyjson.Marshal(elm)
  28. if err != nil {
  29. c.buf.Remove(k)
  30. return false
  31. }
  32. c.buf.Add(k, buf)
  33. return true
  34. }
  35. func (c *ttlCache) String() string {
  36. return "ttl_lru_cache"
  37. }
  38. func (c *ttlCache) Close() error {
  39. if c.buf != nil {
  40. c.buf.Purge()
  41. }
  42. return nil
  43. }