lruexpirecache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cache
  14. import (
  15. "sync"
  16. "time"
  17. "github.com/golang/groupcache/lru"
  18. )
  19. type LRUExpireCache struct {
  20. cache *lru.Cache
  21. lock sync.RWMutex
  22. }
  23. func NewLRUExpireCache(maxSize int) *LRUExpireCache {
  24. return &LRUExpireCache{cache: lru.New(maxSize)}
  25. }
  26. type cacheEntry struct {
  27. value interface{}
  28. expireTime time.Time
  29. }
  30. func (c *LRUExpireCache) Add(key lru.Key, value interface{}, ttl time.Duration) {
  31. c.lock.Lock()
  32. defer c.lock.Unlock()
  33. c.cache.Add(key, &cacheEntry{value, time.Now().Add(ttl)})
  34. // Remove entry from cache after ttl.
  35. time.AfterFunc(ttl, func() { c.remove(key) })
  36. }
  37. func (c *LRUExpireCache) Get(key lru.Key) (interface{}, bool) {
  38. c.lock.RLock()
  39. defer c.lock.RUnlock()
  40. e, ok := c.cache.Get(key)
  41. if !ok {
  42. return nil, false
  43. }
  44. if time.Now().After(e.(*cacheEntry).expireTime) {
  45. go c.remove(key)
  46. return nil, false
  47. }
  48. return e.(*cacheEntry).value, true
  49. }
  50. func (c *LRUExpireCache) remove(key lru.Key) {
  51. c.lock.Lock()
  52. defer c.lock.Unlock()
  53. c.cache.Remove(key)
  54. }