cache.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package cache
  2. import (
  3. "context"
  4. "time"
  5. )
  6. // Cache interface
  7. type Cache interface {
  8. Get(key string) interface{}
  9. Set(key string, val interface{}, timeout time.Duration) error
  10. IsExist(key string) bool
  11. Delete(key string) error
  12. }
  13. // ContextCache interface
  14. type ContextCache interface {
  15. Cache
  16. GetContext(ctx context.Context, key string) interface{}
  17. SetContext(ctx context.Context, key string, val interface{}, timeout time.Duration) error
  18. IsExistContext(ctx context.Context, key string) bool
  19. DeleteContext(ctx context.Context, key string) error
  20. }
  21. // GetContext get value from cache
  22. func GetContext(ctx context.Context, cache Cache, key string) interface{} {
  23. if cache, ok := cache.(ContextCache); ok {
  24. return cache.GetContext(ctx, key)
  25. }
  26. return cache.Get(key)
  27. }
  28. // SetContext set value to cache
  29. func SetContext(ctx context.Context, cache Cache, key string, val interface{}, timeout time.Duration) error {
  30. if cache, ok := cache.(ContextCache); ok {
  31. return cache.SetContext(ctx, key, val, timeout)
  32. }
  33. return cache.Set(key, val, timeout)
  34. }
  35. // IsExistContext check value exists in cache.
  36. func IsExistContext(ctx context.Context, cache Cache, key string) bool {
  37. if cache, ok := cache.(ContextCache); ok {
  38. return cache.IsExistContext(ctx, key)
  39. }
  40. return cache.IsExist(key)
  41. }
  42. // DeleteContext delete value in cache.
  43. func DeleteContext(ctx context.Context, cache Cache, key string) error {
  44. if cache, ok := cache.(ContextCache); ok {
  45. return cache.DeleteContext(ctx, key)
  46. }
  47. return cache.Delete(key)
  48. }