123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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(items ...Element) error {
- if items == nil {
- return nil
- }
- for _, item := range items {
- if item == nil {
- continue
- }
- buf, err := item.Marshal()
- if err != nil {
- return err
- }
- c.buf.Add(item.Key(), 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
- }
|