add context parameter for all functions of package gcache

This commit is contained in:
John Guo 2021-09-17 10:48:08 +08:00
parent 1455e30350
commit 28f70d52ee
12 changed files with 255 additions and 444 deletions

View File

@ -7,6 +7,7 @@
package gdb
import (
"github.com/gogf/gf/internal/intlog"
"time"
)
@ -38,6 +39,10 @@ func (m *Model) Cache(duration time.Duration, name ...string) *Model {
// cache feature is enabled.
func (m *Model) checkAndRemoveCache() {
if m.cacheEnabled && m.cacheDuration < 0 && len(m.cacheName) > 0 {
m.db.GetCache().Ctx(m.GetCtx()).Remove(m.cacheName)
var ctx = m.GetCtx()
_, err := m.db.GetCache().Remove(ctx, m.cacheName)
if err != nil {
intlog.Error(ctx, err)
}
}
}

View File

@ -531,15 +531,18 @@ func (m *Model) UnionAll(unions ...*Model) *Model {
// doGetAllBySql does the select statement on the database.
func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, err error) {
cacheKey := ""
cacheObj := m.db.GetCache().Ctx(m.GetCtx())
var (
ctx = m.GetCtx()
cacheKey = ""
cacheObj = m.db.GetCache()
)
// Retrieve from cache.
if m.cacheEnabled && m.tx == nil {
cacheKey = m.cacheName
if len(cacheKey) == 0 {
cacheKey = sql + ", @PARAMS:" + gconv.String(args)
}
if v, _ := cacheObj.Get(cacheKey); !v.IsNil() {
if v, _ := cacheObj.Get(ctx, cacheKey); !v.IsNil() {
if result, ok := v.Val().(Result); ok {
// In-memory cache.
return result, nil
@ -560,7 +563,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e
// Cache the result.
if cacheKey != "" && err == nil {
if m.cacheDuration < 0 {
if _, err := cacheObj.Remove(cacheKey); err != nil {
if _, err := cacheObj.Remove(ctx, cacheKey); err != nil {
intlog.Error(m.GetCtx(), err)
}
} else {
@ -568,7 +571,7 @@ func (m *Model) doGetAllBySql(sql string, args ...interface{}) (result Result, e
if result == nil {
result = Result{}
}
if err := cacheObj.Set(cacheKey, result, m.cacheDuration); err != nil {
if err := cacheObj.Set(ctx, cacheKey, result, m.cacheDuration); err != nil {
intlog.Error(m.GetCtx(), err)
}
}

View File

@ -10,6 +10,7 @@ import (
"fmt"
"github.com/gogf/gf/errors/gcode"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/internal/intlog"
"github.com/gogf/gf/internal/json"
"strings"
@ -37,7 +38,10 @@ func (s *Server) serveHandlerKey(method, path, domain string) string {
// getHandlersWithCache searches the router item with cache feature for given request.
func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*handlerParsedItem, hasHook, hasServe bool) {
method := r.Method
var (
ctx = r.Context()
method = r.Method
)
// Special http method OPTIONS handling.
// It searches the handler with the request method instead of OPTIONS method.
if method == "OPTIONS" {
@ -46,7 +50,8 @@ func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*handlerParsedI
}
}
// Search and cache the router handlers.
value, _ := s.serveCache.GetOrSetFunc(
value, err := s.serveCache.GetOrSetFunc(
ctx,
s.serveHandlerKey(method, r.URL.Path, r.GetHost()),
func() (interface{}, error) {
parsedItems, hasHook, hasServe = s.searchHandlers(method, r.URL.Path, r.GetHost())
@ -55,6 +60,9 @@ func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*handlerParsedI
}
return nil, nil
}, routeCacheDuration)
if err != nil {
intlog.Error(ctx, err)
}
if value != nil {
item := value.Val().(*handlerCacheItem)
return item.parsedItems, item.hasHook, item.hasServe

View File

@ -18,26 +18,20 @@ import (
// Default cache object.
var defaultCache = New()
// Ctx is a chaining function, which shallowly clones current object and sets the context
// for next operation.
func Ctx(ctx context.Context) *Cache {
return defaultCache.Ctx(ctx)
}
// Set sets cache with `key`-`value` pair, which is expired after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the keys of `data` if `duration` < 0 or given `value` is nil.
func Set(key interface{}, value interface{}, duration time.Duration) error {
return defaultCache.Set(key, value, duration)
func Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error {
return defaultCache.Set(ctx, key, value, duration)
}
// Sets batch sets cache with key-value pairs by `data` map, which is expired after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the keys of `data` if `duration` < 0 or given `value` is nil.
func Sets(data map[interface{}]interface{}, duration time.Duration) error {
return defaultCache.Sets(data, duration)
func Sets(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error {
return defaultCache.Sets(ctx, data, duration)
}
// SetIfNotExist sets cache with `key`-`value` pair which is expired after `duration`
@ -46,8 +40,8 @@ func Sets(data map[interface{}]interface{}, duration time.Duration) error {
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil.
func SetIfNotExist(key interface{}, value interface{}, duration time.Duration) (bool, error) {
return defaultCache.SetIfNotExist(key, value, duration)
func SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error) {
return defaultCache.SetIfNotExist(ctx, key, value, duration)
}
// SetIfNotExistFunc sets `key` with result of function `f` and returns true
@ -58,8 +52,8 @@ func SetIfNotExist(key interface{}, value interface{}, duration time.Duration) (
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil.
func SetIfNotExistFunc(key interface{}, f func() (interface{}, error), duration time.Duration) (bool, error) {
return defaultCache.SetIfNotExistFunc(key, f, duration)
func SetIfNotExistFunc(ctx context.Context, key interface{}, f func() (interface{}, error), duration time.Duration) (bool, error) {
return defaultCache.SetIfNotExistFunc(ctx, key, f, duration)
}
// SetIfNotExistFuncLock sets `key` with result of function `f` and returns true
@ -70,15 +64,15 @@ func SetIfNotExistFunc(key interface{}, f func() (interface{}, error), duration
//
// Note that it differs from function `SetIfNotExistFunc` is that the function `f` is executed within
// writing mutex lock for concurrent safety purpose.
func SetIfNotExistFuncLock(key interface{}, f func() (interface{}, error), duration time.Duration) (bool, error) {
return defaultCache.SetIfNotExistFuncLock(key, f, duration)
func SetIfNotExistFuncLock(ctx context.Context, key interface{}, f func() (interface{}, error), duration time.Duration) (bool, error) {
return defaultCache.SetIfNotExistFuncLock(ctx, key, f, duration)
}
// Get retrieves and returns the associated value of given `key`.
// It returns nil if it does not exist, or its value is nil, or it's expired.
// If you would like to check if the `key` exists in the cache, it's better using function Contains.
func Get(key interface{}) (*gvar.Var, error) {
return defaultCache.Get(key)
func Get(ctx context.Context, key interface{}) (*gvar.Var, error) {
return defaultCache.Get(ctx, key)
}
// GetOrSet retrieves and returns the value of `key`, or sets `key`-`value` pair and
@ -88,8 +82,8 @@ func Get(key interface{}) (*gvar.Var, error) {
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing
// if `value` is a function and the function result is nil.
func GetOrSet(key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error) {
return defaultCache.GetOrSet(key, value, duration)
func GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error) {
return defaultCache.GetOrSet(ctx, key, value, duration)
}
// GetOrSetFunc retrieves and returns the value of `key`, or sets `key` with result of
@ -99,8 +93,8 @@ func GetOrSet(key interface{}, value interface{}, duration time.Duration) (*gvar
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing
// if `value` is a function and the function result is nil.
func GetOrSetFunc(key interface{}, f func() (interface{}, error), duration time.Duration) (*gvar.Var, error) {
return defaultCache.GetOrSetFunc(key, f, duration)
func GetOrSetFunc(ctx context.Context, key interface{}, f func() (interface{}, error), duration time.Duration) (*gvar.Var, error) {
return defaultCache.GetOrSetFunc(ctx, key, f, duration)
}
// GetOrSetFuncLock retrieves and returns the value of `key`, or sets `key` with result of
@ -113,13 +107,13 @@ func GetOrSetFunc(key interface{}, f func() (interface{}, error), duration time.
//
// Note that it differs from function `GetOrSetFunc` is that the function `f` is executed within
// writing mutex lock for concurrent safety purpose.
func GetOrSetFuncLock(key interface{}, f func() (interface{}, error), duration time.Duration) (*gvar.Var, error) {
return defaultCache.GetOrSetFuncLock(key, f, duration)
func GetOrSetFuncLock(ctx context.Context, key interface{}, f func() (interface{}, error), duration time.Duration) (*gvar.Var, error) {
return defaultCache.GetOrSetFuncLock(ctx, key, f, duration)
}
// Contains checks and returns true if `key` exists in the cache, or else returns false.
func Contains(key interface{}) (bool, error) {
return defaultCache.Contains(key)
func Contains(ctx context.Context, key interface{}) (bool, error) {
return defaultCache.Contains(ctx, key)
}
// GetExpire retrieves and returns the expiration of `key` in the cache.
@ -127,19 +121,19 @@ func Contains(key interface{}) (bool, error) {
// Note that,
// It returns 0 if the `key` does not expire.
// It returns -1 if the `key` does not exist in the cache.
func GetExpire(key interface{}) (time.Duration, error) {
return defaultCache.GetExpire(key)
func GetExpire(ctx context.Context, key interface{}) (time.Duration, error) {
return defaultCache.GetExpire(ctx, key)
}
// Remove deletes one or more keys from cache, and returns its value.
// If multiple keys are given, it returns the value of the last deleted item.
func Remove(keys ...interface{}) (value *gvar.Var, err error) {
return defaultCache.Remove(keys...)
func Remove(ctx context.Context, keys ...interface{}) (value *gvar.Var, err error) {
return defaultCache.Remove(ctx, keys...)
}
// Removes deletes `keys` in the cache.
func Removes(keys []interface{}) error {
return defaultCache.Removes(keys)
func Removes(ctx context.Context, keys []interface{}) error {
return defaultCache.Removes(ctx, keys)
}
// Update updates the value of `key` without changing its expiration and returns the old value.
@ -147,41 +141,41 @@ func Removes(keys []interface{}) error {
//
// It deletes the `key` if given `value` is nil.
// It does nothing if `key` does not exist in the cache.
func Update(key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) {
return defaultCache.Update(key, value)
func Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) {
return defaultCache.Update(ctx, key, value)
}
// UpdateExpire updates the expiration of `key` and returns the old expiration duration value.
//
// It returns -1 and does nothing if the `key` does not exist in the cache.
// It deletes the `key` if `duration` < 0.
func UpdateExpire(key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
return defaultCache.UpdateExpire(key, duration)
func UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
return defaultCache.UpdateExpire(ctx, key, duration)
}
// Size returns the number of items in the cache.
func Size() (int, error) {
return defaultCache.Size()
func Size(ctx context.Context) (int, error) {
return defaultCache.Size(ctx)
}
// Data returns a copy of all key-value pairs in the cache as map type.
// Note that this function may lead lots of memory usage, you can implement this function
// if necessary.
func Data() (map[interface{}]interface{}, error) {
return defaultCache.Data()
func Data(ctx context.Context) (map[interface{}]interface{}, error) {
return defaultCache.Data(ctx)
}
// Keys returns all keys in the cache as slice.
func Keys() ([]interface{}, error) {
return defaultCache.Keys()
func Keys(ctx context.Context) ([]interface{}, error) {
return defaultCache.Keys(ctx)
}
// KeyStrings returns all keys in the cache as string slice.
func KeyStrings() ([]string, error) {
return defaultCache.KeyStrings()
func KeyStrings(ctx context.Context) ([]string, error) {
return defaultCache.KeyStrings(ctx)
}
// Values returns all values in the cache as slice.
func Values() ([]interface{}, error) {
return defaultCache.Values()
func Values(ctx context.Context) ([]interface{}, error) {
return defaultCache.Values(ctx)
}

View File

@ -15,16 +15,18 @@ import (
// Cache struct.
type Cache struct {
adapter Adapter // Adapter for cache features.
ctx context.Context // Context for operations.
localAdapter
}
// localAdapter is alias of Adapter, for embedded attribute purpose only.
type localAdapter = Adapter
// New creates and returns a new cache object using default memory adapter.
// Note that the LRU feature is only available using memory adapter.
func New(lruCap ...int) *Cache {
memAdapter := NewAdapterMemory(lruCap...)
c := &Cache{
adapter: memAdapter,
localAdapter: memAdapter,
}
// 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.
@ -35,52 +37,28 @@ func New(lruCap ...int) *Cache {
// NewWithAdapter creates and returns a Cache object with given Adapter implements.
func NewWithAdapter(adapter Adapter) *Cache {
return &Cache{
adapter: adapter,
localAdapter: adapter,
}
}
// Clone returns a shallow copy of current object.
func (c *Cache) Clone() *Cache {
return &Cache{
adapter: c.adapter,
ctx: c.ctx,
}
}
// Ctx is a chaining function, which shallowly clones current object and sets the context
// for next operation.
func (c *Cache) Ctx(ctx context.Context) *Cache {
newCache := c.Clone()
newCache.ctx = ctx
return newCache
}
// 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.adapter = adapter
c.localAdapter = adapter
}
// Removes deletes `keys` in the cache.
func (c *Cache) Removes(keys []interface{}) error {
_, err := c.Remove(keys...)
func (c *Cache) Removes(ctx context.Context, keys []interface{}) error {
_, err := c.Remove(ctx, keys...)
return err
}
// KeyStrings returns all keys in the cache as string slice.
func (c *Cache) KeyStrings() ([]string, error) {
keys, err := c.Keys()
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
}
// KeyStrings returns all keys in the cache as string slice.
func (c *Cache) getCtx() context.Context {
if c.ctx == nil {
return context.Background()
}
return c.ctx
}

View File

@ -1,175 +0,0 @@
// 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 (
"github.com/gogf/gf/container/gvar"
"time"
)
// Set sets cache with `key`-`value` pair, which is expired after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the keys of `data` if `duration` < 0 or given `value` is nil.
func (c *Cache) Set(key interface{}, value interface{}, duration time.Duration) error {
return c.adapter.Set(c.getCtx(), key, value, duration)
}
// Sets batch sets cache with key-value pairs by `data` map, which is expired after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the keys of `data` if `duration` < 0 or given `value` is nil.
func (c *Cache) Sets(data map[interface{}]interface{}, duration time.Duration) error {
return c.adapter.Sets(c.getCtx(), data, duration)
}
// SetIfNotExist sets cache with `key`-`value` pair which is expired after `duration`
// if `key` does not exist in the cache. It returns true the `key` does not exist in the
// cache, and it sets `value` successfully to the cache, or else it returns false.
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil.
func (c *Cache) SetIfNotExist(key interface{}, value interface{}, duration time.Duration) (bool, error) {
return c.adapter.SetIfNotExist(c.getCtx(), key, value, duration)
}
// SetIfNotExistFunc sets `key` with result of function `f` and returns true
// if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists.
//
// The parameter `value` can be type of `func() interface{}`, but it does nothing if its
// result is nil.
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil.
func (c *Cache) SetIfNotExistFunc(key interface{}, f func() (interface{}, error), duration time.Duration) (bool, error) {
return c.adapter.SetIfNotExistFunc(c.getCtx(), key, f, duration)
}
// SetIfNotExistFuncLock sets `key` with result of function `f` and returns true
// if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists.
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil.
//
// Note that it differs from function `SetIfNotExistFunc` is that the function `f` is executed within
// writing mutex lock for concurrent safety purpose.
func (c *Cache) SetIfNotExistFuncLock(key interface{}, f func() (interface{}, error), duration time.Duration) (bool, error) {
return c.adapter.SetIfNotExistFuncLock(c.getCtx(), key, f, duration)
}
// Get retrieves and returns the associated value of given `key`.
// It returns nil if it does not exist, or its value is nil, or it's expired.
// If you would like to check if the `key` exists in the cache, it's better using function Contains.
func (c *Cache) Get(key interface{}) (*gvar.Var, error) {
return c.adapter.Get(c.getCtx(), key)
}
// GetOrSet retrieves and returns the value of `key`, or sets `key`-`value` pair and
// returns `value` if `key` does not exist in the cache. The key-value pair expires
// after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing
// if `value` is a function and the function result is nil.
func (c *Cache) GetOrSet(key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error) {
return c.adapter.GetOrSet(c.getCtx(), key, value, duration)
}
// GetOrSetFunc retrieves and returns the value of `key`, or sets `key` with result of
// function `f` and returns its result if `key` does not exist in the cache. The key-value
// pair expires after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing
// if `value` is a function and the function result is nil.
func (c *Cache) GetOrSetFunc(key interface{}, f func() (interface{}, error), duration time.Duration) (*gvar.Var, error) {
return c.adapter.GetOrSetFunc(c.getCtx(), key, f, duration)
}
// GetOrSetFuncLock retrieves and returns the value of `key`, or sets `key` with result of
// function `f` and returns its result if `key` does not exist in the cache. The key-value
// pair expires after `duration`.
//
// It does not expire if `duration` == 0.
// It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing
// if `value` is a function and the function result is nil.
//
// Note that it differs from function `GetOrSetFunc` is that the function `f` is executed within
// writing mutex lock for concurrent safety purpose.
func (c *Cache) GetOrSetFuncLock(key interface{}, f func() (interface{}, error), duration time.Duration) (*gvar.Var, error) {
return c.adapter.GetOrSetFuncLock(c.getCtx(), key, f, duration)
}
// Contains checks and returns true if `key` exists in the cache, or else returns false.
func (c *Cache) Contains(key interface{}) (bool, error) {
return c.adapter.Contains(c.getCtx(), key)
}
// GetExpire retrieves and returns the expiration of `key` in the cache.
//
// Note that,
// It returns 0 if the `key` does not expire.
// It returns -1 if the `key` does not exist in the cache.
func (c *Cache) GetExpire(key interface{}) (time.Duration, error) {
return c.adapter.GetExpire(c.getCtx(), key)
}
// Remove deletes one or more keys from cache, and returns its value.
// If multiple keys are given, it returns the value of the last deleted item.
func (c *Cache) Remove(keys ...interface{}) (value *gvar.Var, err error) {
return c.adapter.Remove(c.getCtx(), keys...)
}
// Update updates the value of `key` without changing its expiration and returns the old value.
// The returned value `exist` is false if the `key` does not exist in the cache.
//
// It deletes the `key` if given `value` is nil.
// It does nothing if `key` does not exist in the cache.
func (c *Cache) Update(key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) {
return c.adapter.Update(c.getCtx(), key, value)
}
// UpdateExpire updates the expiration of `key` and returns the old expiration duration value.
//
// It returns -1 and does nothing if the `key` does not exist in the cache.
// It deletes the `key` if `duration` < 0.
func (c *Cache) UpdateExpire(key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
return c.adapter.UpdateExpire(c.getCtx(), key, duration)
}
// Size returns the number of items in the cache.
func (c *Cache) Size() (size int, err error) {
return c.adapter.Size(c.getCtx())
}
// Data returns a copy of all key-value pairs in the cache as map type.
// Note that this function may lead lots of memory usage, you can implement this function
// if necessary.
func (c *Cache) Data() (map[interface{}]interface{}, error) {
return c.adapter.Data(c.getCtx())
}
// Keys returns all keys in the cache as slice.
func (c *Cache) Keys() ([]interface{}, error) {
return c.adapter.Keys(c.getCtx())
}
// Values returns all values in the cache as slice.
func (c *Cache) Values() ([]interface{}, error) {
return c.adapter.Values(c.getCtx())
}
// Clear clears all data of the cache.
// Note that this function is sensitive and should be carefully used.
func (c *Cache) Clear() error {
return c.adapter.Clear(c.getCtx())
}
// Close closes the cache if necessary.
func (c *Cache) Close() error {
return c.adapter.Close(c.getCtx())
}

View File

@ -9,6 +9,7 @@
package gcache_test
import (
"context"
"testing"
"github.com/gogf/gf/os/gcache"
@ -23,7 +24,7 @@ func Benchmark_CacheSet(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
localCache.Set(i, i, 0)
localCache.Set(ctx, i, i, 0)
i++
}
})
@ -33,7 +34,7 @@ func Benchmark_CacheGet(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
localCache.Get(i)
localCache.Get(ctx, i)
i++
}
})
@ -43,7 +44,7 @@ func Benchmark_CacheRemove(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
localCache.Remove(i)
localCache.Remove(ctx, i)
i++
}
})
@ -53,7 +54,7 @@ func Benchmark_CacheLruSet(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
localCacheLru.Set(i, i, 0)
localCacheLru.Set(ctx, i, i, 0)
i++
}
})
@ -63,7 +64,7 @@ func Benchmark_CacheLruGet(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
localCacheLru.Get(i)
localCacheLru.Get(ctx, i)
i++
}
})
@ -73,7 +74,7 @@ func Benchmark_CacheLruRemove(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
localCacheLru.Remove(i)
localCacheLru.Remove(context.TODO(), i)
i++
}
})

View File

@ -22,13 +22,17 @@ import (
"github.com/gogf/gf/test/gtest"
)
var (
ctx = context.Background()
)
func TestCache_GCache_Set(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
t.AssertNil(gcache.Set(1, 11, 0))
defer gcache.Remove(g.Slice{1, 2, 3}...)
v, _ := gcache.Get(1)
t.AssertNil(gcache.Set(ctx, 1, 11, 0))
defer gcache.Remove(ctx, g.Slice{1, 2, 3}...)
v, _ := gcache.Get(ctx, 1)
t.Assert(v, 11)
b, _ := gcache.Contains(1)
b, _ := gcache.Contains(ctx, 1)
t.Assert(b, true)
})
}
@ -36,11 +40,11 @@ func TestCache_GCache_Set(t *testing.T) {
func TestCache_Set(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
c := gcache.New()
defer c.Close()
t.Assert(c.Set(1, 11, 0), nil)
v, _ := c.Get(1)
defer c.Close(ctx)
t.Assert(c.Set(ctx, 1, 11, 0), nil)
v, _ := c.Get(ctx, 1)
t.Assert(v, 11)
b, _ := c.Contains(1)
b, _ := c.Contains(ctx, 1)
t.Assert(b, true)
})
}
@ -48,25 +52,25 @@ func TestCache_Set(t *testing.T) {
func TestCache_Set_Expire(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
t.Assert(cache.Set(2, 22, 100*time.Millisecond), nil)
v, _ := cache.Get(2)
t.Assert(cache.Set(ctx, 2, 22, 100*time.Millisecond), nil)
v, _ := cache.Get(ctx, 2)
t.Assert(v, 22)
time.Sleep(200 * time.Millisecond)
v, _ = cache.Get(2)
v, _ = cache.Get(ctx, 2)
t.Assert(v, nil)
time.Sleep(3 * time.Second)
n, _ := cache.Size()
n, _ := cache.Size(ctx)
t.Assert(n, 0)
t.Assert(cache.Close(), nil)
t.Assert(cache.Close(ctx), nil)
})
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
t.Assert(cache.Set(1, 11, 100*time.Millisecond), nil)
v, _ := cache.Get(1)
t.Assert(cache.Set(ctx, 1, 11, 100*time.Millisecond), nil)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
time.Sleep(200 * time.Millisecond)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, nil)
})
}
@ -75,31 +79,31 @@ func TestCache_Update(t *testing.T) {
// gcache
gtest.C(t, func(t *gtest.T) {
key := guid.S()
t.AssertNil(gcache.Set(key, 11, 3*time.Second))
expire1, _ := gcache.GetExpire(key)
oldValue, exist, err := gcache.Update(key, 12)
t.AssertNil(gcache.Set(ctx, key, 11, 3*time.Second))
expire1, _ := gcache.GetExpire(ctx, key)
oldValue, exist, err := gcache.Update(ctx, key, 12)
t.AssertNil(err)
t.Assert(oldValue, 11)
t.Assert(exist, true)
expire2, _ := gcache.GetExpire(key)
v, _ := gcache.Get(key)
expire2, _ := gcache.GetExpire(ctx, key)
v, _ := gcache.Get(ctx, key)
t.Assert(v, 12)
t.Assert(math.Ceil(expire1.Seconds()), math.Ceil(expire2.Seconds()))
})
// gcache.Cache
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
t.AssertNil(cache.Set(1, 11, 3*time.Second))
t.AssertNil(cache.Set(ctx, 1, 11, 3*time.Second))
oldValue, exist, err := cache.Update(1, 12)
oldValue, exist, err := cache.Update(ctx, 1, 12)
t.AssertNil(err)
t.Assert(oldValue, 11)
t.Assert(exist, true)
expire1, _ := cache.GetExpire(1)
expire2, _ := cache.GetExpire(1)
v, _ := cache.Get(1)
expire1, _ := cache.GetExpire(ctx, 1)
expire2, _ := cache.GetExpire(ctx, 1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 12)
t.Assert(math.Ceil(expire1.Seconds()), math.Ceil(expire2.Seconds()))
})
@ -109,33 +113,33 @@ func TestCache_UpdateExpire(t *testing.T) {
// gcache
gtest.C(t, func(t *gtest.T) {
key := guid.S()
t.AssertNil(gcache.Set(key, 11, 3*time.Second))
defer gcache.Remove(key)
oldExpire, _ := gcache.GetExpire(key)
t.AssertNil(gcache.Set(ctx, key, 11, 3*time.Second))
defer gcache.Remove(ctx, key)
oldExpire, _ := gcache.GetExpire(ctx, key)
newExpire := 10 * time.Second
oldExpire2, err := gcache.UpdateExpire(key, newExpire)
oldExpire2, err := gcache.UpdateExpire(ctx, key, newExpire)
t.AssertNil(err)
t.Assert(oldExpire2, oldExpire)
e, _ := gcache.GetExpire(key)
e, _ := gcache.GetExpire(ctx, key)
t.AssertNE(e, oldExpire)
e, _ = gcache.GetExpire(key)
e, _ = gcache.GetExpire(ctx, key)
t.Assert(math.Ceil(e.Seconds()), 10)
})
// gcache.Cache
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
t.AssertNil(cache.Set(1, 11, 3*time.Second))
oldExpire, _ := cache.GetExpire(1)
t.AssertNil(cache.Set(ctx, 1, 11, 3*time.Second))
oldExpire, _ := cache.GetExpire(ctx, 1)
newExpire := 10 * time.Second
oldExpire2, err := cache.UpdateExpire(1, newExpire)
oldExpire2, err := cache.UpdateExpire(ctx, 1, newExpire)
t.AssertNil(err)
t.Assert(oldExpire2, oldExpire)
e, _ := cache.GetExpire(1)
e, _ := cache.GetExpire(ctx, 1)
t.AssertNE(e, oldExpire)
e, _ = cache.GetExpire(1)
e, _ = cache.GetExpire(ctx, 1)
t.Assert(math.Ceil(e.Seconds()), 10)
})
}
@ -144,11 +148,11 @@ func TestCache_Keys_Values(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
c := gcache.New()
for i := 0; i < 10; i++ {
t.Assert(c.Set(i, i*10, 0), nil)
t.Assert(c.Set(ctx, i, i*10, 0), nil)
}
var (
keys, _ = c.Keys()
values, _ = c.Values()
keys, _ = c.Keys(ctx)
values, _ = c.Values(ctx)
)
t.Assert(len(keys), 10)
t.Assert(len(values), 10)
@ -161,30 +165,30 @@ func TestCache_LRU(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New(2)
for i := 0; i < 10; i++ {
t.AssertNil(cache.Set(i, i, 0))
t.AssertNil(cache.Set(ctx, i, i, 0))
}
n, _ := cache.Size()
n, _ := cache.Size(ctx)
t.Assert(n, 10)
v, _ := cache.Get(6)
v, _ := cache.Get(ctx, 6)
t.Assert(v, 6)
time.Sleep(4 * time.Second)
n, _ = cache.Size()
n, _ = cache.Size(ctx)
t.Assert(n, 2)
v, _ = cache.Get(6)
v, _ = cache.Get(ctx, 6)
t.Assert(v, 6)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, nil)
t.Assert(cache.Close(), nil)
t.Assert(cache.Close(ctx), nil)
})
}
func TestCache_LRU_expire(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New(2)
t.Assert(cache.Set(1, nil, 1000), nil)
n, _ := cache.Size()
t.Assert(cache.Set(ctx, 1, nil, 1000), nil)
n, _ := cache.Size(ctx)
t.Assert(n, 1)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, nil)
})
@ -193,40 +197,40 @@ func TestCache_LRU_expire(t *testing.T) {
func TestCache_SetIfNotExist(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
ok, err := cache.SetIfNotExist(1, 11, 0)
ok, err := cache.SetIfNotExist(ctx, 1, 11, 0)
t.AssertNil(err)
t.Assert(ok, true)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
ok, err = cache.SetIfNotExist(1, 22, 0)
ok, err = cache.SetIfNotExist(ctx, 1, 22, 0)
t.AssertNil(err)
t.Assert(ok, false)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
ok, err = cache.SetIfNotExist(2, 22, 0)
ok, err = cache.SetIfNotExist(ctx, 2, 22, 0)
t.AssertNil(err)
t.Assert(ok, true)
v, _ = cache.Get(2)
v, _ = cache.Get(ctx, 2)
t.Assert(v, 22)
gcache.Remove(g.Slice{1, 2, 3}...)
ok, err = gcache.SetIfNotExist(1, 11, 0)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
ok, err = gcache.SetIfNotExist(ctx, 1, 11, 0)
t.AssertNil(err)
t.Assert(ok, true)
v, _ = gcache.Get(1)
v, _ = gcache.Get(ctx, 1)
t.Assert(v, 11)
ok, err = gcache.SetIfNotExist(1, 22, 0)
ok, err = gcache.SetIfNotExist(ctx, 1, 22, 0)
t.AssertNil(err)
t.Assert(ok, false)
v, _ = gcache.Get(1)
v, _ = gcache.Get(ctx, 1)
t.Assert(v, 11)
})
}
@ -234,43 +238,43 @@ func TestCache_SetIfNotExist(t *testing.T) {
func TestCache_SetIfNotExistFunc(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
exist, err := cache.SetIfNotExistFunc(1, func() (interface{}, error) {
exist, err := cache.SetIfNotExistFunc(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
t.AssertNil(err)
t.Assert(exist, true)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
exist, err = cache.SetIfNotExistFunc(1, func() (interface{}, error) {
exist, err = cache.SetIfNotExistFunc(ctx, 1, func() (interface{}, error) {
return 22, nil
}, 0)
t.AssertNil(err)
t.Assert(exist, false)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
})
gtest.C(t, func(t *gtest.T) {
gcache.Remove(g.Slice{1, 2, 3}...)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
ok, err := gcache.SetIfNotExistFunc(1, func() (interface{}, error) {
ok, err := gcache.SetIfNotExistFunc(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
t.AssertNil(err)
t.Assert(ok, true)
v, _ := gcache.Get(1)
v, _ := gcache.Get(ctx, 1)
t.Assert(v, 11)
ok, err = gcache.SetIfNotExistFunc(1, func() (interface{}, error) {
ok, err = gcache.SetIfNotExistFunc(ctx, 1, func() (interface{}, error) {
return 22, nil
}, 0)
t.AssertNil(err)
t.Assert(ok, false)
v, _ = gcache.Get(1)
v, _ = gcache.Get(ctx, 1)
t.Assert(v, 11)
})
}
@ -278,43 +282,43 @@ func TestCache_SetIfNotExistFunc(t *testing.T) {
func TestCache_SetIfNotExistFuncLock(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
exist, err := cache.SetIfNotExistFuncLock(1, func() (interface{}, error) {
exist, err := cache.SetIfNotExistFuncLock(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
t.AssertNil(err)
t.Assert(exist, true)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
exist, err = cache.SetIfNotExistFuncLock(1, func() (interface{}, error) {
exist, err = cache.SetIfNotExistFuncLock(ctx, 1, func() (interface{}, error) {
return 22, nil
}, 0)
t.AssertNil(err)
t.Assert(exist, false)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
})
gtest.C(t, func(t *gtest.T) {
gcache.Remove(g.Slice{1, 2, 3}...)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
exist, err := gcache.SetIfNotExistFuncLock(1, func() (interface{}, error) {
exist, err := gcache.SetIfNotExistFuncLock(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
t.AssertNil(err)
t.Assert(exist, true)
v, _ := gcache.Get(1)
v, _ := gcache.Get(ctx, 1)
t.Assert(v, 11)
exist, err = gcache.SetIfNotExistFuncLock(1, func() (interface{}, error) {
exist, err = gcache.SetIfNotExistFuncLock(ctx, 1, func() (interface{}, error) {
return 22, nil
}, 0)
t.AssertNil(err)
t.Assert(exist, false)
v, _ = gcache.Get(1)
v, _ = gcache.Get(ctx, 1)
t.Assert(v, 11)
})
}
@ -322,13 +326,13 @@ func TestCache_SetIfNotExistFuncLock(t *testing.T) {
func TestCache_Sets(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
t.AssertNil(cache.Sets(g.MapAnyAny{1: 11, 2: 22}, 0))
v, _ := cache.Get(1)
t.AssertNil(cache.Sets(ctx, g.MapAnyAny{1: 11, 2: 22}, 0))
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
gcache.Remove(g.Slice{1, 2, 3}...)
t.AssertNil(gcache.Sets(g.MapAnyAny{1: 11, 2: 22}, 0))
v, _ = cache.Get(1)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
t.AssertNil(gcache.Sets(ctx, g.MapAnyAny{1: 11, 2: 22}, 0))
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
})
}
@ -336,35 +340,35 @@ func TestCache_Sets(t *testing.T) {
func TestCache_GetOrSet(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
value, err := cache.GetOrSet(1, 11, 0)
value, err := cache.GetOrSet(ctx, 1, 11, 0)
t.AssertNil(err)
t.Assert(value, 11)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
value, err = cache.GetOrSet(1, 111, 0)
value, err = cache.GetOrSet(ctx, 1, 111, 0)
t.AssertNil(err)
t.Assert(value, 11)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
})
gtest.C(t, func(t *gtest.T) {
gcache.Remove(g.Slice{1, 2, 3}...)
value, err := gcache.GetOrSet(1, 11, 0)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
value, err := gcache.GetOrSet(ctx, 1, 11, 0)
t.AssertNil(err)
t.Assert(value, 11)
v, err := gcache.Get(1)
v, err := gcache.Get(ctx, 1)
t.AssertNil(err)
t.Assert(v, 11)
value, err = gcache.GetOrSet(1, 111, 0)
value, err = gcache.GetOrSet(ctx, 1, 111, 0)
t.AssertNil(err)
t.Assert(value, 11)
v, err = gcache.Get(1)
v, err = gcache.Get(ctx, 1)
t.AssertNil(err)
t.Assert(v, 11)
})
@ -373,30 +377,30 @@ func TestCache_GetOrSet(t *testing.T) {
func TestCache_GetOrSetFunc(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
cache.GetOrSetFunc(1, func() (interface{}, error) {
cache.GetOrSetFunc(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
cache.GetOrSetFunc(1, func() (interface{}, error) {
cache.GetOrSetFunc(ctx, 1, func() (interface{}, error) {
return 111, nil
}, 0)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
gcache.Remove(g.Slice{1, 2, 3}...)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
gcache.GetOrSetFunc(1, func() (interface{}, error) {
gcache.GetOrSetFunc(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
gcache.GetOrSetFunc(1, func() (interface{}, error) {
gcache.GetOrSetFunc(ctx, 1, func() (interface{}, error) {
return 111, nil
}, 0)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
})
}
@ -404,29 +408,29 @@ func TestCache_GetOrSetFunc(t *testing.T) {
func TestCache_GetOrSetFuncLock(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
cache.GetOrSetFuncLock(1, func() (interface{}, error) {
cache.GetOrSetFuncLock(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
cache.GetOrSetFuncLock(1, func() (interface{}, error) {
cache.GetOrSetFuncLock(ctx, 1, func() (interface{}, error) {
return 111, nil
}, 0)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
gcache.Remove(g.Slice{1, 2, 3}...)
gcache.GetOrSetFuncLock(1, func() (interface{}, error) {
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
gcache.GetOrSetFuncLock(ctx, 1, func() (interface{}, error) {
return 11, nil
}, 0)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
gcache.GetOrSetFuncLock(1, func() (interface{}, error) {
gcache.GetOrSetFuncLock(ctx, 1, func() (interface{}, error) {
return 111, nil
}, 0)
v, _ = cache.Get(1)
v, _ = cache.Get(ctx, 1)
t.Assert(v, 11)
})
}
@ -434,9 +438,9 @@ func TestCache_GetOrSetFuncLock(t *testing.T) {
func TestCache_Clear(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
cache.Sets(g.MapAnyAny{1: 11, 2: 22}, 0)
cache.Clear()
n, _ := cache.Size()
cache.Sets(ctx, g.MapAnyAny{1: 11, 2: 22}, 0)
cache.Clear(ctx)
n, _ := cache.Size(ctx)
t.Assert(n, 0)
})
}
@ -448,7 +452,7 @@ func TestCache_SetConcurrency(t *testing.T) {
go func() {
for {
pool.Add(func() {
cache.SetIfNotExist(1, 11, 10)
cache.SetIfNotExist(ctx, 1, 11, 10)
})
}
}()
@ -460,7 +464,7 @@ func TestCache_SetConcurrency(t *testing.T) {
go func() {
for {
pool.Add(func() {
cache.SetIfNotExist(1, nil, 10)
cache.SetIfNotExist(ctx, 1, nil, 10)
})
}
}()
@ -475,58 +479,58 @@ func TestCache_Basic(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
{
cache := gcache.New()
cache.Sets(g.MapAnyAny{1: 11, 2: 22}, 0)
b, _ := cache.Contains(1)
cache.Sets(ctx, g.MapAnyAny{1: 11, 2: 22}, 0)
b, _ := cache.Contains(ctx, 1)
t.Assert(b, true)
v, _ := cache.Get(1)
v, _ := cache.Get(ctx, 1)
t.Assert(v, 11)
data, _ := cache.Data()
data, _ := cache.Data(ctx)
t.Assert(data[1], 11)
t.Assert(data[2], 22)
t.Assert(data[3], nil)
n, _ := cache.Size()
n, _ := cache.Size(ctx)
t.Assert(n, 2)
keys, _ := cache.Keys()
keys, _ := cache.Keys(ctx)
t.Assert(gset.NewFrom(g.Slice{1, 2}).Equal(gset.NewFrom(keys)), true)
keyStrs, _ := cache.KeyStrings()
keyStrs, _ := cache.KeyStrings(ctx)
t.Assert(gset.NewFrom(g.Slice{"1", "2"}).Equal(gset.NewFrom(keyStrs)), true)
values, _ := cache.Values()
values, _ := cache.Values(ctx)
t.Assert(gset.NewFrom(g.Slice{11, 22}).Equal(gset.NewFrom(values)), true)
removeData1, _ := cache.Remove(1)
removeData1, _ := cache.Remove(ctx, 1)
t.Assert(removeData1, 11)
n, _ = cache.Size()
n, _ = cache.Size(ctx)
t.Assert(n, 1)
cache.Remove(2)
n, _ = cache.Size()
cache.Remove(ctx, 2)
n, _ = cache.Size(ctx)
t.Assert(n, 0)
}
gcache.Remove(g.Slice{1, 2, 3}...)
gcache.Remove(ctx, g.Slice{1, 2, 3}...)
{
gcache.Sets(g.MapAnyAny{1: 11, 2: 22}, 0)
b, _ := gcache.Contains(1)
gcache.Sets(ctx, g.MapAnyAny{1: 11, 2: 22}, 0)
b, _ := gcache.Contains(ctx, 1)
t.Assert(b, true)
v, _ := gcache.Get(1)
v, _ := gcache.Get(ctx, 1)
t.Assert(v, 11)
data, _ := gcache.Data()
data, _ := gcache.Data(ctx)
t.Assert(data[1], 11)
t.Assert(data[2], 22)
t.Assert(data[3], nil)
n, _ := gcache.Size()
n, _ := gcache.Size(ctx)
t.Assert(n, 2)
keys, _ := gcache.Keys()
keys, _ := gcache.Keys(ctx)
t.Assert(gset.NewFrom(g.Slice{1, 2}).Equal(gset.NewFrom(keys)), true)
keyStrs, _ := gcache.KeyStrings()
keyStrs, _ := gcache.KeyStrings(ctx)
t.Assert(gset.NewFrom(g.Slice{"1", "2"}).Equal(gset.NewFrom(keyStrs)), true)
values, _ := gcache.Values()
values, _ := gcache.Values(ctx)
t.Assert(gset.NewFrom(g.Slice{11, 22}).Equal(gset.NewFrom(values)), true)
removeData1, _ := gcache.Remove(1)
removeData1, _ := gcache.Remove(ctx, 1)
t.Assert(removeData1, 11)
n, _ = gcache.Size()
n, _ = gcache.Size(ctx)
t.Assert(n, 1)
gcache.Remove(2)
n, _ = gcache.Size()
gcache.Remove(ctx, 2)
n, _ = gcache.Size(ctx)
t.Assert(n, 0)
}
})
@ -535,43 +539,32 @@ func TestCache_Basic(t *testing.T) {
func TestCache_Removes(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
t.AssertNil(cache.Set(1, 11, 0))
t.AssertNil(cache.Set(2, 22, 0))
t.AssertNil(cache.Set(3, 33, 0))
t.AssertNil(cache.Removes(g.Slice{2, 3}))
t.AssertNil(cache.Set(ctx, 1, 11, 0))
t.AssertNil(cache.Set(ctx, 2, 22, 0))
t.AssertNil(cache.Set(ctx, 3, 33, 0))
t.AssertNil(cache.Removes(ctx, g.Slice{2, 3}))
ok, err := cache.Contains(1)
ok, err := cache.Contains(ctx, 1)
t.AssertNil(err)
t.Assert(ok, true)
ok, err = cache.Contains(2)
ok, err = cache.Contains(ctx, 2)
t.AssertNil(err)
t.Assert(ok, false)
})
gtest.C(t, func(t *gtest.T) {
t.AssertNil(gcache.Set(1, 11, 0))
t.AssertNil(gcache.Set(2, 22, 0))
t.AssertNil(gcache.Set(3, 33, 0))
t.AssertNil(gcache.Removes(g.Slice{2, 3}))
t.AssertNil(gcache.Set(ctx, 1, 11, 0))
t.AssertNil(gcache.Set(ctx, 2, 22, 0))
t.AssertNil(gcache.Set(ctx, 3, 33, 0))
t.AssertNil(gcache.Removes(ctx, g.Slice{2, 3}))
ok, err := gcache.Contains(1)
ok, err := gcache.Contains(ctx, 1)
t.AssertNil(err)
t.Assert(ok, true)
ok, err = gcache.Contains(2)
ok, err = gcache.Contains(ctx, 2)
t.AssertNil(err)
t.Assert(ok, false)
})
}
func TestCache_Ctx(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
cache := gcache.New()
cache.Ctx(context.Background()).Sets(g.MapAnyAny{1: 11, 2: 22}, 0)
b, _ := cache.Contains(1)
t.Assert(b, true)
v, _ := cache.Get(1)
t.Assert(v, 11)
})
}

View File

@ -7,6 +7,8 @@
package gfile
import (
"context"
"github.com/gogf/gf/internal/intlog"
"github.com/gogf/gf/os/gcache"
"github.com/gogf/gf/os/gcmd"
"github.com/gogf/gf/os/gfsnotify"
@ -37,18 +39,25 @@ func GetContentsWithCache(path string, duration ...time.Duration) string {
// If there's no content in the cache, it will read it from disk file specified by <path>.
// The parameter <expire> specifies the caching time for this file content in seconds.
func GetBytesWithCache(path string, duration ...time.Duration) []byte {
key := cacheKey(path)
expire := cacheExpire
var (
ctx = context.Background()
expire = cacheExpire
cacheKey = commandEnvKeyForCache + path
)
if len(duration) > 0 {
expire = duration[0]
}
r, _ := internalCache.GetOrSetFuncLock(key, func() (interface{}, error) {
r, _ := internalCache.GetOrSetFuncLock(ctx, cacheKey, func() (interface{}, error) {
b := GetBytes(path)
if b != nil {
// Adding this <path> to gfsnotify,
// it will clear its cache if there's any changes of the file.
_, _ = gfsnotify.Add(path, func(event *gfsnotify.Event) {
internalCache.Remove(key)
_, err := internalCache.Remove(ctx, cacheKey)
if err != nil {
intlog.Error(ctx, err)
}
gfsnotify.Exit()
})
}
@ -59,8 +68,3 @@ func GetBytesWithCache(path string, duration ...time.Duration) []byte {
}
return nil
}
// cacheKey produces the cache key for gcache.
func cacheKey(path string) string {
return commandEnvKeyForCache + path
}

View File

@ -24,7 +24,7 @@ func (w *Watcher) watchLoop() {
// Event listening.
case ev := <-w.watcher.Events:
// Filter the repeated event in custom duration.
w.cache.SetIfNotExist(ev.String(), func() (interface{}, error) {
w.cache.SetIfNotExist(context.Background(), ev.String(), func() (interface{}, error) {
w.events.Push(&Event{
event: ev,
Path: ev.Name,

View File

@ -71,5 +71,5 @@ func (m *Manager) TTL() time.Duration {
// UpdateSessionTTL updates the ttl for given session.
func (m *Manager) UpdateSessionTTL(sessionId string, data *gmap.StrAnyMap) {
m.sessionData.Set(sessionId, data, m.ttl)
m.sessionData.Set(context.Background(), sessionId, data, m.ttl)
}

View File

@ -43,7 +43,7 @@ func (s *Session) init() {
var err error
if s.id != "" {
// Retrieve memory session data from manager.
if r, _ := s.manager.sessionData.Get(s.id); r != nil {
if r, _ := s.manager.sessionData.Get(s.ctx, s.id); r != nil {
s.data = r.Val().(*gmap.StrAnyMap)
intlog.Print(s.ctx, "session init data:", s.data)
}