gcache_cache.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2018 gf Author(https://github.com/gogf/gf). 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. "github.com/gogf/gf/container/gvar"
  9. "github.com/gogf/gf/os/gtimer"
  10. "github.com/gogf/gf/util/gconv"
  11. "time"
  12. )
  13. // Cache struct.
  14. type Cache struct {
  15. Adapter // Adapter for cache features.
  16. }
  17. // New creates and returns a new cache object using default memory adapter.
  18. // Note that the LRU feature is only available using memory adapter.
  19. func New(lruCap ...int) *Cache {
  20. memAdapter := newAdapterMemory(lruCap...)
  21. c := &Cache{
  22. Adapter: memAdapter,
  23. }
  24. // Here may be a "timer leak" if adapter is manually changed from memory adapter.
  25. // Do not worry about this, as adapter is less changed and it dose nothing if it's not used.
  26. gtimer.AddSingleton(time.Second, memAdapter.syncEventAndClearExpired)
  27. return c
  28. }
  29. // SetAdapter changes the adapter for this cache.
  30. // Be very note that, this setting function is not concurrent-safe, which means you should not call
  31. // this setting function concurrently in multiple goroutines.
  32. func (c *Cache) SetAdapter(adapter Adapter) {
  33. c.Adapter = adapter
  34. }
  35. // GetVar retrieves and returns the value of <key> as gvar.Var.
  36. func (c *Cache) GetVar(key interface{}) (*gvar.Var, error) {
  37. v, err := c.Get(key)
  38. return gvar.New(v), err
  39. }
  40. // Removes deletes <keys> in the cache.
  41. // Deprecated, use Remove instead.
  42. func (c *Cache) Removes(keys []interface{}) error {
  43. _, err := c.Remove(keys...)
  44. return err
  45. }
  46. // KeyStrings returns all keys in the cache as string slice.
  47. func (c *Cache) KeyStrings() ([]string, error) {
  48. keys, err := c.Keys()
  49. if err != nil {
  50. return nil, err
  51. }
  52. return gconv.Strings(keys), nil
  53. }