gcache

package
v1.18.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2024 License: MIT Imports: 13 Imported by: 2

Documentation

Overview

Package gcache provides kinds of cache management for process.

It provides a concurrent-safe in-memory cache adapter for process in default.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contains

func Contains(ctx context.Context, key interface{}) (bool, error)

Contains checks and returns true if `key` exists in the cache, or else returns false.

func Data

func Data(ctx context.Context) (map[interface{}]interface{}, error)

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 Get

func Get(ctx context.Context, key interface{}) (*gvar.Var, error)

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 GetExpire

func GetExpire(ctx context.Context, key interface{}) (time.Duration, error)

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 GetOrSet

func GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error)

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 GetOrSetFunc

func GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error)

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 GetOrSetFuncLock

func GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error)

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 KeyStrings

func KeyStrings(ctx context.Context) ([]string, error)

KeyStrings returns all keys in the cache as string slice.

func Keys

func Keys(ctx context.Context) ([]interface{}, error)

Keys returns all keys in the cache as slice.

func MustContains

func MustContains(ctx context.Context, key interface{}) bool

MustContains acts like Contains, but it panics if any error occurs.

func MustData

func MustData(ctx context.Context) map[interface{}]interface{}

MustData acts like Data, but it panics if any error occurs.

func MustGet

func MustGet(ctx context.Context, key interface{}) *gvar.Var

MustGet acts like Get, but it panics if any error occurs.

func MustGetExpire

func MustGetExpire(ctx context.Context, key interface{}) time.Duration

MustGetExpire acts like GetExpire, but it panics if any error occurs.

func MustGetOrSet

func MustGetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) *gvar.Var

MustGetOrSet acts like GetOrSet, but it panics if any error occurs.

func MustGetOrSetFunc

func MustGetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var

MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs.

func MustGetOrSetFuncLock

func MustGetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var

MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs.

func MustKeyStrings

func MustKeyStrings(ctx context.Context) []string

MustKeyStrings acts like KeyStrings, but it panics if any error occurs.

func MustKeys

func MustKeys(ctx context.Context) []interface{}

MustKeys acts like Keys, but it panics if any error occurs.

func MustSize

func MustSize(ctx context.Context) int

MustSize acts like Size, but it panics if any error occurs.

func MustValues

func MustValues(ctx context.Context) []interface{}

MustValues acts like Values, but it panics if any error occurs.

func Remove

func Remove(ctx context.Context, keys ...interface{}) (value *gvar.Var, err error)

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 Removes

func Removes(ctx context.Context, keys []interface{}) error

Removes deletes `keys` in the cache.

func Set

func Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error

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 SetIfNotExist

func SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error)

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 SetIfNotExistFunc

func SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error)

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 SetIfNotExistFuncLock

func SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error)

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 SetMap

func SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error

SetMap 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 Size

func Size(ctx context.Context) (int, error)

Size returns the number of items in the cache.

func Update

func Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error)

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 UpdateExpire

func UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error)

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 Values

func Values(ctx context.Context) ([]interface{}, error)

Values returns all values in the cache as slice.

Types

type Adapter

type Adapter interface {
	// 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.
	Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error

	// SetMap 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.
	SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error

	// 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.
	SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (ok bool, err error)

	// 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.
	SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error)

	// 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.
	SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error)

	// 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.
	Get(ctx context.Context, key interface{}) (*gvar.Var, error)

	// 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.
	GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error)

	// 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.
	GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error)

	// 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.
	GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error)

	// Contains checks and returns true if `key` exists in the cache, or else returns false.
	Contains(ctx context.Context, key interface{}) (bool, error)

	// Size returns the number of items in the cache.
	Size(ctx context.Context) (size int, err error)

	// 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.
	Data(ctx context.Context) (data map[interface{}]interface{}, err error)

	// Keys returns all keys in the cache as slice.
	Keys(ctx context.Context) (keys []interface{}, err error)

	// Values returns all values in the cache as slice.
	Values(ctx context.Context) (values []interface{}, err error)

	// 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.
	Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error)

	// 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.
	UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error)

	// 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.
	GetExpire(ctx context.Context, key interface{}) (time.Duration, error)

	// 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.
	Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error)

	// Clear clears all data of the cache.
	// Note that this function is sensitive and should be carefully used.
	Clear(ctx context.Context) error

	// Close closes the cache if necessary.
	Close(ctx context.Context) error
}

Adapter is the core adapter for cache features implements.

Note that the implementer itself should guarantee the concurrent safety of these functions.

func NewAdapterMemory

func NewAdapterMemory(lruCap ...int) Adapter

NewAdapterMemory creates and returns a new memory cache object.

func NewAdapterRedis

func NewAdapterRedis(redis *gredis.Redis) Adapter

NewAdapterRedis creates and returns a new memory cache object.

type AdapterMemory

type AdapterMemory struct {
	// contains filtered or unexported fields
}

AdapterMemory is an adapter implements using memory.

func (*AdapterMemory) Clear

func (c *AdapterMemory) Clear(ctx context.Context) error

Clear clears all data of the cache. Note that this function is sensitive and should be carefully used.

func (*AdapterMemory) Close

func (c *AdapterMemory) Close(ctx context.Context) error

Close closes the cache.

func (*AdapterMemory) Contains

func (c *AdapterMemory) Contains(ctx context.Context, key interface{}) (bool, error)

Contains checks and returns true if `key` exists in the cache, or else returns false.

func (*AdapterMemory) Data

func (c *AdapterMemory) Data(ctx context.Context) (map[interface{}]interface{}, error)

Data returns a copy of all key-value pairs in the cache as map type.

func (*AdapterMemory) Get

func (c *AdapterMemory) Get(ctx context.Context, key interface{}) (*gvar.Var, error)

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 (*AdapterMemory) GetExpire

func (c *AdapterMemory) GetExpire(ctx context.Context, key interface{}) (time.Duration, error)

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 (*AdapterMemory) GetOrSet

func (c *AdapterMemory) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error)

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 (*AdapterMemory) GetOrSetFunc

func (c *AdapterMemory) GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error)

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 (*AdapterMemory) GetOrSetFuncLock

func (c *AdapterMemory) GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error)

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 (*AdapterMemory) Keys

func (c *AdapterMemory) Keys(ctx context.Context) ([]interface{}, error)

Keys returns all keys in the cache as slice.

func (*AdapterMemory) Remove

func (c *AdapterMemory) Remove(ctx context.Context, keys ...interface{}) (*gvar.Var, error)

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 (*AdapterMemory) Set

func (c *AdapterMemory) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error

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 (*AdapterMemory) SetIfNotExist

func (c *AdapterMemory) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error)

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 (*AdapterMemory) SetIfNotExistFunc

func (c *AdapterMemory) SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error)

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 (*AdapterMemory) SetIfNotExistFuncLock

func (c *AdapterMemory) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error)

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 (*AdapterMemory) SetMap

func (c *AdapterMemory) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error

SetMap 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 (*AdapterMemory) Size

func (c *AdapterMemory) Size(ctx context.Context) (size int, err error)

Size returns the size of the cache.

func (*AdapterMemory) Update

func (c *AdapterMemory) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error)

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 (*AdapterMemory) UpdateExpire

func (c *AdapterMemory) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error)

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 (*AdapterMemory) Values

func (c *AdapterMemory) Values(ctx context.Context) ([]interface{}, error)

Values returns all values in the cache as slice.

type AdapterRedis

type AdapterRedis struct {
	// contains filtered or unexported fields
}

AdapterRedis is the gcache adapter implements using Redis server.

func (*AdapterRedis) Clear

func (c *AdapterRedis) Clear(ctx context.Context) (err error)

Clear clears all data of the cache. Note that this function is sensitive and should be carefully used. It uses `FLUSHDB` command in redis server, which might be disabled in server.

func (*AdapterRedis) Close

func (c *AdapterRedis) Close(ctx context.Context) error

Close closes the cache.

func (*AdapterRedis) Contains

func (c *AdapterRedis) Contains(ctx context.Context, key interface{}) (bool, error)

Contains checks and returns true if `key` exists in the cache, or else returns false.

func (*AdapterRedis) Data

func (c *AdapterRedis) Data(ctx context.Context) (map[interface{}]interface{}, error)

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 (*AdapterRedis) Get

func (c *AdapterRedis) Get(ctx context.Context, key interface{}) (*gvar.Var, error)

Get retrieves and returns the associated value of given <key>. It returns nil if it does not exist or its value is nil.

func (*AdapterRedis) GetExpire

func (c *AdapterRedis) GetExpire(ctx context.Context, key interface{}) (time.Duration, error)

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 (*AdapterRedis) GetOrSet

func (c *AdapterRedis) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error)

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 (*AdapterRedis) GetOrSetFunc

func (c *AdapterRedis) GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error)

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 (*AdapterRedis) GetOrSetFuncLock

func (c *AdapterRedis) GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error)

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 (*AdapterRedis) Keys

func (c *AdapterRedis) Keys(ctx context.Context) ([]interface{}, error)

Keys returns all keys in the cache as slice.

func (*AdapterRedis) Remove

func (c *AdapterRedis) Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error)

Remove deletes the one or more keys from cache, and returns its value. If multiple keys are given, it returns the value of the deleted last item.

func (*AdapterRedis) Set

func (c *AdapterRedis) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (err error)

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 (*AdapterRedis) SetIfNotExist

func (c *AdapterRedis) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error)

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 (*AdapterRedis) SetIfNotExistFunc

func (c *AdapterRedis) SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error)

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 (*AdapterRedis) SetIfNotExistFuncLock

func (c *AdapterRedis) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error)

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 (*AdapterRedis) SetMap

func (c *AdapterRedis) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error

SetMap 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 (*AdapterRedis) Size

func (c *AdapterRedis) Size(ctx context.Context) (size int, err error)

Size returns the number of items in the cache.

func (*AdapterRedis) Update

func (c *AdapterRedis) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error)

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 (*AdapterRedis) UpdateExpire

func (c *AdapterRedis) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error)

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 (*AdapterRedis) Values

func (c *AdapterRedis) Values(ctx context.Context) ([]interface{}, error)

Values returns all values in the cache as slice.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache struct.

func New

func New(lruCap ...int) *Cache

New creates and returns a new cache object using default memory adapter. Note that the LRU feature is only available using memory adapter.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly.
c := gcache.New()

// Set cache without expiration
c.Set(ctx, "k1", "v1", 0)

// Get cache
v, _ := c.Get(ctx, "k1")
fmt.Println(v)

// Get cache size
n, _ := c.Size(ctx)
fmt.Println(n)

// Does the specified key name exist in the cache
b, _ := c.Contains(ctx, "k1")
fmt.Println(b)

// Delete and return the deleted key value
fmt.Println(c.Remove(ctx, "k1"))

// Close the cache object and let the GC reclaim resources

c.Close(ctx)
Output:

v1
1
true
v1 <nil>

func NewWithAdapter

func NewWithAdapter(adapter Adapter) *Cache

NewWithAdapter creates and returns a Cache object with given Adapter implements.

func (*Cache) GetAdapter

func (c *Cache) GetAdapter() Adapter

GetAdapter returns the adapter that is set in current Cache.

Example
package main

import (
	"fmt"
	"time"

	"github.com/joy12825/gf/database/gredis"
	"github.com/joy12825/gf/os/gcache"
	"github.com/joy12825/gf/os/gctx"
)

func main() {
	var (
		err         error
		ctx         = gctx.New()
		cache       = gcache.New()
		redisConfig = &gredis.Config{
			Address: "127.0.0.1:6379",
			Db:      10,
		}
		cacheKey   = `key`
		cacheValue = `value`
	)
	redis, err := gredis.New(redisConfig)
	if err != nil {
		panic(err)
	}
	cache.SetAdapter(gcache.NewAdapterRedis(redis))

	// Set and Get using cache object.
	err = cache.Set(ctx, cacheKey, cacheValue, time.Second)
	if err != nil {
		panic(err)
	}
	fmt.Println(cache.MustGet(ctx, cacheKey).String())

	// Get using redis client.
	v, err := cache.GetAdapter().(*gcache.AdapterRedis).Get(ctx, cacheKey)
	fmt.Println(err)
	fmt.Println(v.String())

	// May Output:
	// value
	// <nil>
	// value
}
Output:

func (*Cache) KeyStrings

func (c *Cache) KeyStrings(ctx context.Context) ([]string, error)

KeyStrings returns all keys in the cache as string slice.

Example
c := gcache.New()

c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0)

// KeyStrings returns all keys in the cache as string slice.
keys, _ := c.KeyStrings(ctx)
fmt.Println(keys)

// May Output:
// [k1 k2]
Output:

func (*Cache) MustContains

func (c *Cache) MustContains(ctx context.Context, key interface{}) bool

MustContains acts like Contains, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// Set Cache
c.Set(ctx, "k", "v", 0)

// MustContains returns true if `key` exists in the cache, or else returns false.
// return true
data := c.MustContains(ctx, "k")
fmt.Println(data)

// return false
data1 := c.MustContains(ctx, "k1")
fmt.Println(data1)
Output:

true
false

func (*Cache) MustData

func (c *Cache) MustData(ctx context.Context) map[interface{}]interface{}

MustData acts like Data, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0)

data := c.MustData(ctx)
fmt.Println(data)

// May Output:
// map[k1:v1 k2:v2]
Output:

func (*Cache) MustGet

func (c *Cache) MustGet(ctx context.Context, key interface{}) *gvar.Var

MustGet acts like Get, but it panics if any error occurs.

Example
// Intercepting panic exception information
// err is empty, so panic is not performed
defer func() {
	if r := recover(); r != nil {
		fmt.Println("recover...:", r)
	}
}()

// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// Set Cache Object
c.Set(ctx, "k1", "v1", 0)

// MustGet acts like Get, but it panics if any error occurs.
k2 := c.MustGet(ctx, "k2")
fmt.Println(k2)

k1 := c.MustGet(ctx, "k1")
fmt.Println(k1)
Output:

v1

func (*Cache) MustGetExpire

func (c *Cache) MustGetExpire(ctx context.Context, key interface{}) time.Duration

MustGetExpire acts like GetExpire, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// Set cache without expiration
c.Set(ctx, "k", "v", 10000*time.Millisecond)

// MustGetExpire acts like GetExpire, but it panics if any error occurs.
expire := c.MustGetExpire(ctx, "k")
fmt.Println(expire)

// May Output:
// 10s
Output:

func (*Cache) MustGetOrSet

func (c *Cache) MustGetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) *gvar.Var

MustGetOrSet acts like GetOrSet, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// MustGetOrSet acts like GetOrSet, but it panics if any error occurs.
k1 := c.MustGetOrSet(ctx, "k1", "v1", 0)
fmt.Println(k1)

k2 := c.MustGetOrSet(ctx, "k1", "v2", 0)
fmt.Println(k2)
Output:

v1
v1

func (*Cache) MustGetOrSetFunc

func (c *Cache) MustGetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var

MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs.
c.MustGetOrSetFunc(ctx, "k1", func(ctx context.Context) (value interface{}, err error) {
	return "v1", nil
}, 10000*time.Millisecond)
v := c.MustGet(ctx, "k1")
fmt.Println(v)

c.MustGetOrSetFunc(ctx, "k2", func(ctx context.Context) (value interface{}, err error) {
	return nil, nil
}, 10000*time.Millisecond)
v1 := c.MustGet(ctx, "k2")
fmt.Println(v1)
Output:

v1

func (*Cache) MustGetOrSetFuncLock

func (c *Cache) MustGetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var

MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs.
c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) {
	return "v1", nil
}, 0)
v := c.MustGet(ctx, "k1")
fmt.Println(v)

// Modification failed
c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) {
	return "update v1", nil
}, 0)
v = c.MustGet(ctx, "k1")
fmt.Println(v)
Output:

v1
v1

func (*Cache) MustKeyStrings

func (c *Cache) MustKeyStrings(ctx context.Context) []string

MustKeyStrings acts like KeyStrings, but it panics if any error occurs.

Example
c := gcache.New()

c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0)

// MustKeyStrings returns all keys in the cache as string slice.
// MustKeyStrings acts like KeyStrings, but it panics if any error occurs.
keys := c.MustKeyStrings(ctx)
fmt.Println(keys)

// May Output:
// [k1 k2]
Output:

func (*Cache) MustKeys

func (c *Cache) MustKeys(ctx context.Context) []interface{}

MustKeys acts like Keys, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2"}, 0)

// MustKeys acts like Keys, but it panics if any error occurs.
keys1 := c.MustKeys(ctx)
fmt.Println(keys1)

// May Output:
// [k1 k2]
Output:

func (*Cache) MustSize

func (c *Cache) MustSize(ctx context.Context) int

MustSize acts like Size, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// Add 10 elements without expiration
for i := 0; i < 10; i++ {
	c.Set(ctx, i, i, 0)
}

// Size returns the number of items in the cache.
n := c.MustSize(ctx)
fmt.Println(n)
Output:

10

func (*Cache) MustValues

func (c *Cache) MustValues(ctx context.Context) []interface{}

MustValues acts like Values, but it panics if any error occurs.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

// Write value
c.Set(ctx, "k1", "v1", 0)

// MustValues returns all values in the cache as slice.
data := c.MustValues(ctx)
fmt.Println(data)
Output:

[v1]

func (*Cache) Removes

func (c *Cache) Removes(ctx context.Context, keys []interface{}) error

Removes deletes `keys` in the cache.

Example
// Create a cache object,
// Of course, you can also easily use the gcache package method directly
c := gcache.New()

c.SetMap(ctx, g.MapAnyAny{"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"}, 0)

// 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.
c.Removes(ctx, g.Slice{"k1", "k2", "k3"})

data, _ := c.Data(ctx)
fmt.Println(data)
Output:

map[k4:v4]

func (*Cache) SetAdapter

func (c *Cache) SetAdapter(adapter Adapter)

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.

Example
package main

import (
	"fmt"
	"time"

	"github.com/joy12825/gf/database/gredis"
	"github.com/joy12825/gf/os/gcache"
	"github.com/joy12825/gf/os/gctx"
)

func main() {
	var (
		err         error
		ctx         = gctx.New()
		cache       = gcache.New()
		redisConfig = &gredis.Config{
			Address: "127.0.0.1:6379",
			Db:      9,
		}
		cacheKey   = `key`
		cacheValue = `value`
	)
	// Create redis client object.
	redis, err := gredis.New(redisConfig)
	if err != nil {
		panic(err)
	}
	// Create redis cache adapter and set it to cache object.
	cache.SetAdapter(gcache.NewAdapterRedis(redis))

	// Set and Get using cache object.
	err = cache.Set(ctx, cacheKey, cacheValue, time.Second)
	if err != nil {
		panic(err)
	}
	fmt.Println(cache.MustGet(ctx, cacheKey).String())

	// Get using redis client.
	fmt.Println(redis.MustDo(ctx, "GET", cacheKey).String())

	// May Output:
	// value
	// value
}
Output:

type Func

type Func func(ctx context.Context) (value interface{}, err error)

Func is the cache function that calculates and returns the value.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL