ttl_cache.go 972 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package cache
  2. import (
  3. "github.com/hashicorp/golang-lru/v2/expirable"
  4. "time"
  5. )
  6. type ttlCache struct {
  7. buf *expirable.LRU[string, []byte]
  8. }
  9. //goland:noinspection GoUnusedExportedFunction
  10. func NewTTLCache(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) error {
  16. var k = elm.Key()
  17. buf, ok := c.buf.Get(k)
  18. if !ok {
  19. return ErrorNotFound
  20. }
  21. if err := elm.Unmarshal(buf); err != nil {
  22. c.buf.Remove(k)
  23. return err
  24. }
  25. return nil
  26. }
  27. func (c *ttlCache) Set(items ...Element) error {
  28. if items == nil {
  29. return nil
  30. }
  31. for _, item := range items {
  32. if item == nil {
  33. continue
  34. }
  35. buf, err := item.Marshal()
  36. if err != nil {
  37. return err
  38. }
  39. c.buf.Add(item.Key(), buf)
  40. }
  41. return nil
  42. }
  43. func (c *ttlCache) String() string {
  44. return "ttl_lru_cache"
  45. }
  46. func (c *ttlCache) Close() error {
  47. if c.buf != nil {
  48. c.buf.Purge()
  49. }
  50. return nil
  51. }