Files
gf/os/gcache/gcache_cache.go

66 lines
1.9 KiB
Go
Raw Normal View History

2021-01-17 21:46:25 +08:00
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gcache
import (
2021-01-26 14:11:36 +08:00
"context"
2021-11-15 20:26:31 +08:00
"time"
2021-10-11 21:41:56 +08:00
"github.com/gogf/gf/v2/os/gtimer"
"github.com/gogf/gf/v2/util/gconv"
)
2019-06-10 21:23:49 +08:00
// Cache struct.
type Cache struct {
localAdapter
}
// localAdapter is alias of Adapter, for embedded attribute purpose only.
type localAdapter = Adapter
2020-09-26 20:47:29 +08:00
// New creates and returns a new cache object using default memory adapter.
// Note that the LRU feature is only available using memory adapter.
2019-06-19 09:06:52 +08:00
func New(lruCap ...int) *Cache {
memAdapter := NewAdapterMemory(lruCap...)
2019-06-19 09:06:52 +08:00
c := &Cache{
localAdapter: memAdapter,
2019-06-19 09:06:52 +08:00
}
2020-09-26 20:47:29 +08:00
// Here may be a "timer leak" if adapter is manually changed from memory adapter.
// Do not worry about this, as adapter is less changed, and it does nothing if it's not used.
2021-11-27 01:10:00 +08:00
gtimer.AddSingleton(context.Background(), time.Second, memAdapter.(*AdapterMemory).syncEventAndClearExpired)
2019-06-19 09:06:52 +08:00
return c
}
// NewWithAdapter creates and returns a Cache object with given Adapter implements.
func NewWithAdapter(adapter Adapter) *Cache {
return &Cache{
localAdapter: adapter,
2021-01-26 14:11:36 +08:00
}
}
2020-09-26 20:47:29 +08:00
// SetAdapter changes the adapter for this cache.
// Be very note that, this setting function is not concurrent-safe, which means you should not call
// this setting function concurrently in multiple goroutines.
func (c *Cache) SetAdapter(adapter Adapter) {
c.localAdapter = adapter
2020-09-26 20:47:29 +08:00
}
2021-08-27 00:01:15 +08:00
// Removes deletes `keys` in the cache.
func (c *Cache) Removes(ctx context.Context, keys []interface{}) error {
_, err := c.Remove(ctx, keys...)
return err
2020-09-26 20:47:29 +08:00
}
// KeyStrings returns all keys in the cache as string slice.
func (c *Cache) KeyStrings(ctx context.Context) ([]string, error) {
keys, err := c.Keys(ctx)
if err != nil {
return nil, err
}
return gconv.Strings(keys), nil
2019-06-19 09:06:52 +08:00
}