gcache_cache.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gcache
  7. import (
  8. "context"
  9. "time"
  10. "github.com/gogf/gf/v2/os/gtimer"
  11. "github.com/gogf/gf/v2/util/gconv"
  12. )
  13. // Cache struct.
  14. type Cache struct {
  15. localAdapter
  16. }
  17. // localAdapter is alias of Adapter, for embedded attribute purpose only.
  18. type localAdapter = Adapter
  19. // New creates and returns a new cache object using default memory adapter.
  20. // Note that the LRU feature is only available using memory adapter.
  21. func New(lruCap ...int) *Cache {
  22. memAdapter := NewAdapterMemory(lruCap...)
  23. c := &Cache{
  24. localAdapter: memAdapter,
  25. }
  26. // Here may be a "timer leak" if adapter is manually changed from memory adapter.
  27. // Do not worry about this, as adapter is less changed, and it does nothing if it's not used.
  28. gtimer.AddSingleton(context.Background(), time.Second, memAdapter.(*AdapterMemory).syncEventAndClearExpired)
  29. return c
  30. }
  31. // NewWithAdapter creates and returns a Cache object with given Adapter implements.
  32. func NewWithAdapter(adapter Adapter) *Cache {
  33. return &Cache{
  34. localAdapter: adapter,
  35. }
  36. }
  37. // SetAdapter changes the adapter for this cache.
  38. // Be very note that, this setting function is not concurrent-safe, which means you should not call
  39. // this setting function concurrently in multiple goroutines.
  40. func (c *Cache) SetAdapter(adapter Adapter) {
  41. c.localAdapter = adapter
  42. }
  43. // GetAdapter returns the adapter that is set in current Cache.
  44. func (c *Cache) GetAdapter() Adapter {
  45. return c.localAdapter
  46. }
  47. // Removes deletes `keys` in the cache.
  48. func (c *Cache) Removes(ctx context.Context, keys []interface{}) error {
  49. _, err := c.Remove(ctx, keys...)
  50. return err
  51. }
  52. // KeyStrings returns all keys in the cache as string slice.
  53. func (c *Cache) KeyStrings(ctx context.Context) ([]string, error) {
  54. keys, err := c.Keys(ctx)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return gconv.Strings(keys), nil
  59. }