1
0

cache.go 700 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package memory_cache
  2. import (
  3. "sync"
  4. )
  5. type Cache struct {
  6. mu sync.RWMutex
  7. items map[string]interface{}
  8. }
  9. func NewCache() *Cache {
  10. return &Cache{
  11. items: make(map[string]interface{}),
  12. }
  13. }
  14. func (c *Cache) Set(key string, value interface{}) {
  15. c.mu.Lock()
  16. defer c.mu.Unlock()
  17. c.items[key] = value
  18. }
  19. func (c *Cache) Get(key string) (interface{}, bool) {
  20. c.mu.RLock()
  21. defer c.mu.RUnlock()
  22. item, found := c.items[key]
  23. return item, found
  24. }
  25. func (c *Cache) Delete(key string) {
  26. c.mu.Lock()
  27. defer c.mu.Unlock()
  28. if _, found := c.items[key]; found {
  29. delete(c.items, key)
  30. }
  31. }
  32. func (c *Cache) Clear() {
  33. c.mu.Lock()
  34. defer c.mu.Unlock()
  35. c.items = make(map[string]interface{})
  36. }