cache.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package cache
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. )
  7. var ErrNotFound = errors.New("not found")
  8. type Cache interface {
  9. Get(context.Context, string) ([]byte, error)
  10. Set(context.Context, string, []byte) error
  11. Delete(context.Context, string) error
  12. }
  13. type Getter interface {
  14. Get(ctx context.Context, key string) ([]byte, error)
  15. }
  16. // A GetterFunc implements Getter with a function.
  17. type GetterFunc func(ctx context.Context, key string) ([]byte, error)
  18. func (f GetterFunc) Get(ctx context.Context, key string) ([]byte, error) {
  19. return f(ctx, key)
  20. }
  21. type Pool interface {
  22. New(name string, getter Getter) Cache
  23. Get(name string) (Cache, bool)
  24. }
  25. func DefaultPool() Pool {
  26. return &defaultPool{
  27. caches: make(map[string]Cache),
  28. }
  29. }
  30. type defaultPool struct {
  31. mu sync.RWMutex
  32. caches map[string]Cache
  33. }
  34. func (p *defaultPool) New(name string, getter Getter) Cache {
  35. c := &mapCache{
  36. m: new(sync.Map),
  37. getter: getter,
  38. }
  39. p.mu.Lock()
  40. p.caches[name] = c
  41. p.mu.Unlock()
  42. return c
  43. }
  44. func (p *defaultPool) Get(name string) (Cache, bool) {
  45. p.mu.RLock()
  46. c, ok := p.caches[name]
  47. p.mu.RUnlock()
  48. return c, ok
  49. }
  50. type mapCache struct {
  51. name string
  52. m *sync.Map
  53. getter Getter
  54. }
  55. func (m *mapCache) Get(ctx context.Context, key string) ([]byte, error) {
  56. v, ok := m.m.Load(key)
  57. if !ok {
  58. b, err := m.getter.Get(ctx, key)
  59. if err != nil {
  60. return nil, err
  61. }
  62. m.m.Store(key, b)
  63. return b, nil
  64. }
  65. return v.([]byte), nil
  66. }
  67. func (m *mapCache) Set(ctx context.Context, key string, value []byte) error {
  68. m.m.Store(key, value)
  69. return nil
  70. }
  71. func (m *mapCache) Delete(ctx context.Context, key string) error {
  72. m.m.Delete(key)
  73. return nil
  74. }