ttl_cache.go 975 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) {
  28. if items == nil {
  29. return
  30. }
  31. go func() {
  32. for _, item := range items {
  33. if item == nil {
  34. continue
  35. }
  36. buf, err := item.Marshal()
  37. if err != nil {
  38. continue
  39. }
  40. c.buf.Add(item.Key(), buf)
  41. }
  42. }()
  43. }
  44. func (c *ttlCache) String() string {
  45. return "ttl_lru_cache"
  46. }
  47. func (c *ttlCache) Close() error {
  48. if c.buf != nil {
  49. c.buf.Purge()
  50. }
  51. return nil
  52. }