cache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package ibm
  13. import (
  14. "time"
  15. "github.com/golang/groupcache/lru"
  16. )
  17. type (
  18. cacheIntf interface {
  19. GetData(key string) (bool, []byte)
  20. PutData(key string, value []byte)
  21. DeleteData(key string)
  22. }
  23. lruCache struct {
  24. lru *lru.Cache
  25. ttl time.Duration
  26. }
  27. cacheObject struct {
  28. timeExpires time.Time
  29. value []byte
  30. }
  31. )
  32. func NewCache(maxEntries int, ttl time.Duration) cacheIntf {
  33. lruCache := &lruCache{
  34. lru: lru.New(maxEntries),
  35. ttl: ttl,
  36. }
  37. return lruCache
  38. }
  39. func (c *lruCache) GetData(key string) (bool, []byte) {
  40. v, ok := c.lru.Get(key)
  41. if !ok {
  42. return false, nil
  43. }
  44. returnedObj := v.(cacheObject)
  45. if time.Now().After(returnedObj.timeExpires) && c.ttl > 0 {
  46. c.DeleteData(key)
  47. return false, nil
  48. }
  49. return true, returnedObj.value
  50. }
  51. func (c *lruCache) PutData(key string, value []byte) {
  52. obj := cacheObject{
  53. timeExpires: time.Now().Add(c.ttl),
  54. value: value,
  55. }
  56. c.lru.Add(key, obj)
  57. }
  58. func (c *lruCache) DeleteData(key string) {
  59. c.lru.Remove(key)
  60. }