Documentation
¶
Overview ¶
Package cache : 数据缓存模块,可定时清理过期数据
Usage
package main
import (
"github.com/xyzj/toolbox/cache"
)
type aaa struct{
Name string
}
func main() {
mycache:=cache.NewEmptyCache[aaa](time.Second*60) // max 1000 data
defer mycache.Close() // clean up and stop zhe data expire check
mycache.Store("123","abc")
v,ok:=mycache.Load("123")
if !ok{
println("key not found")
return
}
println(v)
}
Index ¶
- Constants
- func RandomStringFromCharset(charset string, length int) (string, error)
- func RandomStringFromSets(sets []string, length int) (string, error)
- type AnyCache
- func (ac *AnyCache[T]) Clear()
- func (ac *AnyCache[T]) Close()
- func (ac *AnyCache[T]) Delete(key string)
- func (ac *AnyCache[T]) DeleteMore(keys ...string)
- func (ac *AnyCache[T]) Extension(key string)
- func (ac *AnyCache[T]) ForEach(f func(key string, value T) bool)
- func (ac *AnyCache[T]) Len() int
- func (ac *AnyCache[T]) Load(key string) (T, bool)
- func (ac *AnyCache[T]) LoadOrStore(key string, value T) (T, bool)
- func (ac *AnyCache[T]) SetCleanUp(cleanup time.Duration)
- func (ac *AnyCache[T]) Store(key string, value T) error
- func (ac *AnyCache[T]) StoreWithExpire(key string, value T, expire time.Duration) error
- type Cache
- type EmptyCache
- func (ac *EmptyCache[T]) Clear()
- func (ac *EmptyCache[T]) Close()
- func (ac *EmptyCache[T]) Delete(key string)
- func (ac *EmptyCache[T]) Extension(key string)
- func (ac *EmptyCache[T]) ForEach(f func(key string, value T) bool)
- func (ac *EmptyCache[T]) Len() int
- func (ac *EmptyCache[T]) Load(key string) (T, bool)
- func (ac *EmptyCache[T]) LoadOrStore(key string, value T) (T, bool)
- func (ac *EmptyCache[T]) SetCleanUp(cleanup time.Duration)
- func (ac *EmptyCache[T]) Store(key string, value T) error
- func (ac *EmptyCache[T]) StoreWithExpire(key string, value T, expire time.Duration) error
- type Ring
Constants ¶
const ( CharsetDigits = "0123456789" CharsetLower = "abcdefghijklmnopqrstuvwxyz" CharsetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" CharsetSpecial = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" )
常用字符集常量
Variables ¶
This section is empty.
Functions ¶
func RandomStringFromCharset ¶
RandomStringFromCharset 使用指定的字符集生成指定长度的随机字符串。 使用 crypto/rand 生成随机数并通过拒绝采样(rejection sampling)避免偏差。 如果 charset 为空或 length < 0 则返回错误。
Types ¶
type AnyCache ¶
type AnyCache[T any] struct { // contains filtered or unexported fields }
AnyCache 泛型结构缓存
func NewAnyCache ¶
NewAnyCache initializes a new cache with a specified expiration time. The cache will create a goroutine to periodically check for expired entries. When the cache is no longer needed, it should be closed using the Close() method.
Parameters:
- expire: The duration for which cache entries should be considered valid.
Return: - A pointer to the newly created AnyCache instance.
Example:
cache := NewAnyCache[int](time.Minute * 5)
defer cache.Close()
cache.Store("key1", 100)
value, ok := cache.Load("key1")
if ok {
fmt.Println("Value:", value) // Output: Value: 100
}
func NewAnyCacheWithExpireFunc ¶
func NewAnyCacheWithExpireFunc[T any](expire time.Duration, expireFunc func(map[string]T)) *AnyCache[T]
NewAnyCacheWithExpireFunc initializes a new cache with a specified expiration time and an optional expiration function. The cache will create a goroutine to periodically check for expired entries. When the cache is no longer needed, it should be closed using the Close() method.
Parameters:
- expire: The duration for which cache entries should be considered valid.
- expireFunc: An optional function to be executed when a cache entry expires. The function will receive a map of expired entries, where the key is the entry key and the value is the entry data.
Return: - A pointer to the newly created AnyCache instance.
func (*AnyCache[T]) Clear ¶
func (ac *AnyCache[T]) Clear()
Clear clears all the entries from the cache. If the cache is already closed, this function does nothing.
This function is safe to call concurrently with other methods of the AnyCache.
func (*AnyCache[T]) Close ¶
func (ac *AnyCache[T]) Close()
Close closes this cache. If the cache needs to be used again, it should be reinitialized using the NewAnyCache method. This method stops the cleanup goroutine, sends a signal to close the channel, clears the cache, and sets the cache pointer to nil.
func (*AnyCache[T]) Delete ¶
Delete removes a cache entry with the specified key. If the cache is already closed, this function does nothing.
Parameters:
- key: The unique identifier for the cache entry to be deleted.
Return:
- None
func (*AnyCache[T]) DeleteMore ¶
func (*AnyCache[T]) Extension ¶
Extension extends the expiration time of the specified cache entry by the cache's default expiration duration. If the cache entry does not exist, this function does nothing.
Parameters:
- key: The key of the cache entry to be extended.
This function is safe to call concurrently with other methods of the AnyCache.
func (*AnyCache[T]) ForEach ¶
ForEach iterates over all the entries in the cache and applies the provided function to each entry. The function will be called for each entry, excluding expired entries. If the function returns false, the iteration will be stopped.
Parameters:
- f: A function that takes a key and a value as parameters and returns a boolean value. The function will be called for each entry in the cache.
Return:
- None
func (*AnyCache[T]) Len ¶
Len returns the number of entries in the cache. If the cache is closed, it returns 0.
This function is safe to call concurrently with other methods of the AnyCache.
Parameters:
- ac: A pointer to the AnyCache instance.
Return:
- An integer representing the number of entries in the cache.
func (*AnyCache[T]) Load ¶
Load retrieves the value associated with the given key from the cache. If the key is not found or the entry has expired, it returns the zero value of type T and false.
Parameters:
- key: The unique identifier for the cache entry.
Return:
- The value associated with the given key if found and not expired.
- A boolean value indicating whether the key was found and not expired.
func (*AnyCache[T]) LoadOrStore ¶
LoadOrStore reads or sets a cache entry.
When the key exists: - Returns the cached content and sets the boolean return value to true.
When the key does not exist: - Adds the content to the cache and returns the set content, along with the boolean return value set to false.
Parameters: - key: The unique identifier for the cache entry. - value: The data to be stored in the cache.
Return:
- The value associated with the given key if found and not expired.
- A boolean value indicating whether the key was found and not expired. If the cache is closed, it returns the zero value of type T and false.
func (*AnyCache[T]) SetCleanUp ¶
SetCleanUp sets the cleanup period for the cache. The cleanup period should not be less than 1 second. If the cleanup period is less than 1 second, it will be automatically set to 1 second.
Parameters: - cleanup: The duration for the cleanup period.
func (*AnyCache[T]) Store ¶
Store adds a cache entry with the specified key and value. If the cache is already closed, it returns an error.
Parameters:
- key: The unique identifier for the cache entry.
- value: The data to be stored in the cache.
Return:
- An error if the cache is closed, otherwise nil.
func (*AnyCache[T]) StoreWithExpire ¶
StoreWithExpire adds a cache entry with the specified key, value, and expiration duration. If the cache is already closed, it returns an error.
Parameters:
- key: The unique identifier for the cache entry.
- value: The data to be stored in the cache.
- expire: The duration for which the cache entry should be considered valid.
Return:
- An error if the cache is closed, otherwise nil.
type Cache ¶
type Cache[T any] interface { Close() Clear() Len() int Extension(key string) Store(key string, value T) error StoreWithExpire(key string, value T, expire time.Duration) error Load(key string) (T, bool) LoadOrStore(key string, value T) (T, bool) Delete(key string) ForEach(f func(key string, value T) bool) }
type EmptyCache ¶
type EmptyCache[T any] struct{}
EmptyCache 一个空的cache,不实现任何功能
func NewEmptyCache ¶
func NewEmptyCache() *EmptyCache[struct{}]
func (*EmptyCache[T]) Close ¶
func (ac *EmptyCache[T]) Close()
Close 关闭这个缓存,如果需要再次使用,应调用NewEmptyCache方法重新初始化
func (*EmptyCache[T]) ForEach ¶
func (ac *EmptyCache[T]) ForEach(f func(key string, value T) bool)
ForEach 遍历所有缓存内容
func (*EmptyCache[T]) Load ¶
func (ac *EmptyCache[T]) Load(key string) (T, bool)
Load 读取一个缓存内容,如果不存在,返回false
func (*EmptyCache[T]) LoadOrStore ¶
func (ac *EmptyCache[T]) LoadOrStore(key string, value T) (T, bool)
LoadOrStore 读取或者设置一个缓存内如
当key存在时,返回缓存内容,并设置true 当key不存在时,将内容加入缓存,返回设置内容,并设置false
func (*EmptyCache[T]) SetCleanUp ¶
func (ac *EmptyCache[T]) SetCleanUp(cleanup time.Duration)
SetCleanUp 设置清理周期,不低于1秒
func (*EmptyCache[T]) Store ¶
func (ac *EmptyCache[T]) Store(key string, value T) error
Store 添加缓存内容,如果缓存已关闭,会返回错误
func (*EmptyCache[T]) StoreWithExpire ¶
func (ac *EmptyCache[T]) StoreWithExpire(key string, value T, expire time.Duration) error
StoreWithExpire 添加缓存内容,设置自定义的有效时间,如果缓存已关闭,会返回错误
type Ring ¶
type Ring[T any] struct { // contains filtered or unexported fields }
Ring implements a circular buffer for storing chat completion messages. It provides efficient storage and retrieval of conversation history with automatic memory management through ring buffer overflow handling.
The Ring struct ensures:
- Fixed memory footprint regardless of conversation length
- Preservation of most recent messages when capacity is exceeded
- Thread-safe operations for concurrent access patterns
- JSON serialization support for persistence
func NewRing ¶
New creates a new History instance with the specified context size. The context size determines how many messages can be stored in the circular buffer. When the buffer is full, new messages will overwrite the oldest messages.
Parameters:
- context: Maximum number of messages to store in the history buffer
Returns a new History instance ready for use.
func (*Ring[T]) Clear ¶
func (u *Ring[T]) Clear()
Clear removes all messages from the history buffer by setting all ring elements to nil. The buffer structure remains intact and ready for new messages.
func (*Ring[T]) FromJSON ¶
FromJSON populates the history from a JSON string representation. The existing history is cleared before loading the new messages.
Parameters:
- s: JSON string containing an array of chat completion messages
Returns:
- error: Any error encountered during unmarshaling or invalid JSON format
func (*Ring[T]) Len ¶
Len returns the capacity of the history buffer (not the number of stored messages). This represents the maximum number of messages that can be stored.
func (*Ring[T]) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for the History type. It serializes the history as a JSON array of chat completion messages.
Returns:
- []byte: JSON representation of the message history
- error: Any error encountered during marshaling
func (*Ring[T]) Slice ¶
func (u *Ring[T]) Slice() []T
Slice returns all non-nil messages from the history buffer as a slice. Messages are returned in the order they were stored, with nil entries filtered out. This is the primary method for retrieving the conversation history.
Returns:
- []T: Slice of stored messages in chronological order
func (*Ring[T]) Store ¶
Store adds a single message to the history buffer. If the buffer is full, the oldest message will be overwritten. Always returns true for consistency with interface expectations.
Parameters:
- msg: The chat completion message to store
Returns true to indicate successful storage.
func (*Ring[T]) StoreMany ¶
func (u *Ring[T]) StoreMany(msgs ...T)
StoreMany adds multiple messages to the history buffer in sequence. Each message is stored using the same overflow behavior as Store(). This is more efficient than calling Store() multiple times.
Parameters:
- msgs: Variable number of chat completion messages to store