cache.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package ttl_memory_cache
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type Cache struct {
  7. expiration *time.Duration
  8. cleanupInterval *time.Duration
  9. mu sync.RWMutex
  10. items map[string]Item
  11. }
  12. type Item struct {
  13. Value interface{}
  14. ExpiredAt *time.Time
  15. }
  16. func NewCache(c Config) *Cache {
  17. cache := Cache{
  18. items: make(map[string]Item),
  19. expiration: c.expiration,
  20. cleanupInterval: c.cleanupInterval,
  21. }
  22. if c.cleanupInterval != nil {
  23. go cache.cleanupWorker()
  24. }
  25. return &cache
  26. }
  27. func (c *Cache) Set(key string, value interface{}, expiration *time.Duration) {
  28. item := Item{
  29. Value: value,
  30. }
  31. if expiration != nil {
  32. expiredAt := time.Now().Add(*expiration)
  33. item.ExpiredAt = &expiredAt
  34. } else if c.expiration != nil {
  35. expiredAt := time.Now().Add(*c.expiration)
  36. item.ExpiredAt = &expiredAt
  37. }
  38. c.mu.Lock()
  39. defer c.mu.Unlock()
  40. c.items[key] = item
  41. }
  42. func (c *Cache) Get(key string) (interface{}, bool) {
  43. c.mu.RLock()
  44. defer c.mu.RUnlock()
  45. item, found := c.items[key]
  46. if !found {
  47. return nil, false
  48. }
  49. if item.ExpiredAt != nil && time.Now().After(*item.ExpiredAt) {
  50. c.Delete(key)
  51. return nil, false
  52. }
  53. return item.Value, true
  54. }
  55. func (c *Cache) Delete(key string) {
  56. c.mu.Lock()
  57. defer c.mu.Unlock()
  58. if _, found := c.items[key]; found {
  59. delete(c.items, key)
  60. }
  61. }
  62. func (c *Cache) cleanupWorker() {
  63. for {
  64. <-time.After(*c.cleanupInterval)
  65. if len(c.items) == 0 {
  66. return
  67. }
  68. now := time.Now()
  69. for key, item := range c.items {
  70. if item.ExpiredAt != nil && now.After(*item.ExpiredAt) {
  71. c.Delete(key)
  72. }
  73. }
  74. }
  75. }