Documentation
¶
Overview ¶
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 00:00:00 * @FilePath: \go-cachex\advanced_cache.go * @Description: 高级缓存包装器,支持压缩和泛型,集成队列、热key和分布式锁功能 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 23:13:01 * @FilePath: \go-cachex\cache.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-09 19:15:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 19:15:00 * @FilePath: \go-cachex\client.go * @Description: 缓存客户端统一入口 * * 提供统一的缓存客户端接口,支持多种底层缓存实现(LRU、Ristretto、Redis、Expiring) * 主要功能包括: * - 统一的配置结构 `ClientConfig`,支持不同缓存类型的配置参数 * - 支持 context 的完整 API:Get、Set、SetWithTTL、Del、GetOrCompute * - 便利构造函数:NewLRUClient、NewRistrettoClient、NewRedisClient、NewExpiringClient * - 自动错误处理和参数验证 * - 优雅的资源管理(Close) * * 使用注意: * - 所有操作都支持 context 传入,可以实现超时控制和取消操作 * - Client 内部封装了 CtxCache,提供并发去重和 singleflight 支持 * - 不同缓存类型有不同的配置要求,使用前请确保配置正确 * - 使用完毕后应调用 Close() 方法释放资源 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 18:58:57 * @FilePath: \go-cachex\ctxcache.go * @Description: context 的缓存封装 `CtxCache` * 实现之上提供对上下文取消和并发去重的支持主要功能包括: * - 提供 `GetOrCompute(ctx, key, ttl, loader)` 方法:先尝试从底层缓存读取,未命中时 * 使用内部的 singleflight(flightGroup)对并发加载进行去重,并在 loader 成功后 * 将结果写回底层缓存(带可选 TTL) * - 代理常见的缓存操作(Get/Set/SetWithTTL/Del/Close),使现有的 Handler 可无缝 * 被升级为支持 context 的缓存层 * * 使用注意: * - 传入的 loader 必须尊重 ctx 取消(及时返回),以便在调用方取消时能中断加载 * - 写回缓存的操作是“最佳努力”的:写失败不会影响 loader 的返回结果,但可能 * 导致后续命中率下降 * - 本文件内实现了一个简易的 flightGroup 以代替外部的 singleflight 依赖,适用于 * 常见去重场景,不保证对极端高并发或长时间阻塞的优化需求 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 00:00:00 * @FilePath: \go-cachex\distributed_lock.go * @Description: 分布式锁实现,提供可靠的分布式锁机制 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-06 21:15:15 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 21:16:12 * @FilePath: \go-cachex\expiring.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 00:00:00 * @FilePath: \go-cachex\hotkey.go * @Description: 热key缓存实现,提供灵活的数据字典缓存功能 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-06 22:05:59 * @FilePath: \go-cachex\lru.go * @Description: 简单的 goroutine 安全 LRU 缓存(LRUHandler) * * 提供可选的每项 TTL 支持,键/值以 []byte 表示(内部以 string 存储键) * 该实现适合用作本地内存缓存或测试用例中的轻量缓存 * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-09 22:30:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 22:30:00 * @FilePath: \go-cachex\lru_optimized.go * @Description: 超高性能优化版本的 LRU 缓存实现 * * 主要优化点: * 1. 分片设计减少锁竞争 * 2. 原子操作优化热路径 * 3. 零拷贝字节操作 * 4. 高效的内存池管理 * 5. 批量操作支持 * 6. NUMA友好的内存布局 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 00:00:00 * @FilePath: \go-cachex\pubsub.go * @Description: Redis 发布订阅功能封装,提供傻瓜式调用接口 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 20:48:27 * @FilePath: \go-cachex\queue.go * @Description: Redis队列实现,支持FIFO、优先级队列等多种队列类型 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-06 22:01:16 * @FilePath: \go-cachex\redis.go * @Description: Redis 的缓存适配器(RedisHandler) * 接口映射到 Redis 客户端调用主要职责: * - 提供 Redis 版本的 Get/Set/SetWithTTL/GetTTL/Del/Close 方法实现,返回和接受 []byte * 以保持与抽象 `Handler` 的兼容性 * - 封装连接配置结构 `RedisConfig`,并提供从文件加载配置的辅助函数 * - 适合作为分布式或远程的 L2 缓存(或共享缓存)使用 * * 使用注意: * - 值以二进制形式写入 Redis,序列化/反序列化由调用方负责(这里直接保存 []byte) * - 调用方应管理好配置与凭据(`RedisConfig`),并注意 Redis 客户端的生命周期 * - Redis 操作会使用内部 context(可通过 WithCtx 创建带自定义 ctx 的 handler) * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-06 21:56:05 * @FilePath: \go-cachex\ristretto.go * @Description: Ristretto 适配器(RistrettoHandler) * * 对 dgraph-io/ristretto 的薄包装,满足仓库中的 `Handler` 接口Ristretto * 提供高性能的本地缓存,支持基于成本的驱逐与统计指标使用此适配器 * 可在进程内获得生产级缓存表现,但需要在项目中引入 ristretto 依赖 * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-06 21:35:15 * @FilePath: \go-cachex\sharded.go * @Description: 分片缓存封装(ShardedHandler) * * 将缓存分为多个 shard,每个 shard 使用独立的 Handler 实例(例如多个 LRU) * 适用于降低单个实例的锁竞争或将负载分散到多个后端实例的场景 * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-05 22:55:22 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-06 21:56:49 * @FilePath: \go-cachex\twolevel.go * @Description: 两级缓存封装(TwoLevelHandler) * * 提供 L1(快速、本地)与 L2(容量大或远程)两级缓存组合:L1 命中直接返回, * L1 未命中时回退到 L2 并将数据提升(promote)到 L1, 写入支持同步写入(write-through) * 或异步回填策略 * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-06 22:35:20 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-06 22:35:20 * @FilePath: \go-cachex\validate.go * @Description: 缓存操作的通用验证 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes [email protected] * @Date: 2025-11-19 23:50:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-12-05 13:50:02 * @FilePath: \go-cachex\wrapper.go * @Description: 缓存包装器实现 * * 缓存包装器(CacheWrapper)是一个高阶函数,用于为任意数据加载函数添加Redis缓存功能。 * * 核心特性: * - 泛型支持:支持任意类型的数据缓存 * - 数据压缩:使用Zlib算法压缩缓存数据,节省Redis内存 * - 延迟双删:实现延迟双删策略,保证缓存一致性 * - 错误处理:优雅处理Redis连接错误和数据序列化错误 * - 并发安全:支持高并发访问 * * 使用示例: * loader := CacheWrapper(redisClient, "cache_key", dataLoaderFunc, time.Hour) * result, err := loader(ctx) * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
Index ¶
- Variables
- func LockWithRetry(ctx context.Context, client *redis.Client, key string, config LockConfig, ...) error
- func MutexLock(ctx context.Context, client *redis.Client, key string, ttl time.Duration, ...) error
- func NewRedisOptions(addr, password string, db int) *redis.Options
- func PublishJSON[T any](p *PubSub, ctx context.Context, channel string, message T) error
- func SimplePublish(client *redis.Client, channel string, message interface{}) error
- func ValidateBasicOp(key []byte, initialized, closed bool) error
- func ValidateCapacity(current, max int) error
- func ValidateClosed(closed bool) error
- func ValidateInitialized(initialized bool) error
- func ValidateKey(key []byte) error
- func ValidateTTL(ttl time.Duration) error
- func ValidateValue(value []byte) error
- func ValidateWriteOp(key, value []byte, initialized, closed bool) error
- func ValidateWriteWithTTLOp(key, value []byte, ttl time.Duration, initialized, closed bool) error
- func WithCache(ctx context.Context, c *CtxCache) context.Context
- type AdvancedCache
- func (c *AdvancedCache[T]) BatchGet(ctx context.Context, keys []string) (map[string]T, error)
- func (c *AdvancedCache[T]) BatchSet(ctx context.Context, items map[string]T, ttl ...time.Duration) error
- func (c *AdvancedCache[T]) Clear(ctx context.Context, pattern string) error
- func (c *AdvancedCache[T]) Close() error
- func (c *AdvancedCache[T]) Delete(ctx context.Context, keys ...string) error
- func (c *AdvancedCache[T]) Exists(ctx context.Context, keys ...string) (int64, error)
- func (c *AdvancedCache[T]) Expire(ctx context.Context, key string, ttl time.Duration) error
- func (c *AdvancedCache[T]) Get(ctx context.Context, key string) (T, bool, error)
- func (c *AdvancedCache[T]) GetHotKeyManager() *HotKeyManager
- func (c *AdvancedCache[T]) GetLockManager() *LockManager
- func (c *AdvancedCache[T]) GetMetrics() *CacheMetrics
- func (c *AdvancedCache[T]) GetOrSet(ctx context.Context, key string, fn func() (T, error), ttl ...time.Duration) (T, error)
- func (c *AdvancedCache[T]) GetQueue() *QueueHandler
- func (c *AdvancedCache[T]) Keys(ctx context.Context, pattern string) ([]string, error)
- func (c *AdvancedCache[T]) Ping(ctx context.Context) error
- func (c *AdvancedCache[T]) ResetMetrics()
- func (c *AdvancedCache[T]) Set(ctx context.Context, key string, value T, ttl ...time.Duration) error
- func (c *AdvancedCache[T]) TTL(ctx context.Context, key string) (time.Duration, error)
- func (c *AdvancedCache[T]) Wrap(key string, fn CacheWrapperFunc[T], ttl ...time.Duration) CacheWrapperFunc[T]
- type AdvancedCacheConfig
- type CacheAsideOperation
- type CacheBuilder
- func (b *CacheBuilder) Build() *SmartCache
- func (b *CacheBuilder) OnError(fn func(ctx context.Context, err error)) *CacheBuilder
- func (b *CacheBuilder) OnMiss(fn func(ctx context.Context, key string) (interface{}, error)) *CacheBuilder
- func (b *CacheBuilder) OnSet(fn func(ctx context.Context, key string, value interface{})) *CacheBuilder
- func (b *CacheBuilder) WithCompression(compType CompressionType) *CacheBuilder
- func (b *CacheBuilder) WithHotKey() *CacheBuilder
- func (b *CacheBuilder) WithKeyPattern(pattern string) *CacheBuilder
- func (b *CacheBuilder) WithLock(timeout time.Duration) *CacheBuilder
- func (b *CacheBuilder) WithPubSub() *CacheBuilder
- func (b *CacheBuilder) WithRefreshThreshold(threshold float64) *CacheBuilder
- func (b *CacheBuilder) WithTTL(ttl time.Duration) *CacheBuilder
- type CacheFunc
- type CacheMetrics
- type CacheOption
- func Combine(opts ...CacheOption) CacheOption
- func Match(cases []Case, defaultOpt ...CacheOption) CacheOption
- func When(condition bool, opt CacheOption) CacheOption
- func WhenThen(condition bool, thenOpt, elseOpt CacheOption) CacheOption
- func WithAsyncUpdate() CacheOption
- func WithForceRefresh(force bool) CacheOption
- func WithJitter(percent float64) CacheOption
- func WithRetry(times int) CacheOption
- func WithTTL(ttl time.Duration) CacheOption
- func WithoutCompression() CacheOption
- type CacheOptions
- type CachePattern
- func (p *CachePattern[T]) CacheAside(ctx context.Context, key string, dbLoader func() (T, error), ...) *CacheAsideOperation[T]
- func (p *CachePattern[T]) ReadThrough(ctx context.Context, key string, dbLoader func() (T, error)) (T, error)
- func (p *CachePattern[T]) WriteBehind(ctx context.Context, key string, value T, dbWriter func(T) error) error
- func (p *CachePattern[T]) WriteThrough(ctx context.Context, key string, value T, dbWriter func(T) error) error
- type CacheStrategy
- type CacheType
- type CacheWrapperFunc
- type Case
- type Client
- func NewClient(ctx context.Context, cfg *ClientConfig) (*Client, error)
- func NewExpiringClient(ctx context.Context, cleanupInterval time.Duration) (*Client, error)
- func NewLRUClient(ctx context.Context, capacity int) (*Client, error)
- func NewLRUOptimizedClient(ctx context.Context, capacity int) (*Client, error)
- func NewRedisClient(ctx context.Context, opts *redis.Options) (*Client, error)
- func NewRistrettoClient(ctx context.Context, config *RistrettoConfig) (*Client, error)
- func (c *Client) BatchGet(ctx context.Context, keys [][]byte) ([][]byte, []error)
- func (c *Client) Close() error
- func (c *Client) Del(ctx context.Context, key []byte) error
- func (c *Client) Get(ctx context.Context, key []byte) ([]byte, error)
- func (c *Client) GetConfig() ClientConfig
- func (c *Client) GetOrCompute(ctx context.Context, key []byte, ttl time.Duration, ...) ([]byte, error)
- func (c *Client) GetTTL(ctx context.Context, key []byte) (time.Duration, error)
- func (c *Client) Set(ctx context.Context, key, value []byte) error
- func (c *Client) SetWithTTL(ctx context.Context, key, value []byte, ttl time.Duration) error
- func (c *Client) Stats(ctx context.Context) map[string]interface{}
- func (c *Client) WithContext(ctx context.Context) context.Context
- type ClientConfig
- type CompressionType
- type ContextHandler
- type CtxCache
- func (c *CtxCache) BatchGet(keys [][]byte) ([][]byte, []error)
- func (c *CtxCache) Close() error
- func (c *CtxCache) Del(ctx context.Context, key []byte) error
- func (c *CtxCache) Get(ctx context.Context, key []byte) ([]byte, error)
- func (c *CtxCache) GetOrCompute(ctx context.Context, key []byte, ttl time.Duration, ...) ([]byte, error)
- func (c *CtxCache) GetTTL(ctx context.Context, key []byte) (time.Duration, error)
- func (c *CtxCache) Set(ctx context.Context, key, value []byte) error
- func (c *CtxCache) SetWithTTL(ctx context.Context, key, value []byte, ttl time.Duration) error
- func (c *CtxCache) Stats() map[string]interface{}
- type DataLoader
- type DistributedLock
- func (l *DistributedLock) Extend(ctx context.Context, ttl time.Duration) error
- func (l *DistributedLock) GetStats(ctx context.Context) (*LockStats, error)
- func (l *DistributedLock) IsLocked(ctx context.Context) (bool, error)
- func (l *DistributedLock) Lock(ctx context.Context) error
- func (l *DistributedLock) LockWithTimeout(ctx context.Context, timeout time.Duration) error
- func (l *DistributedLock) TTL(ctx context.Context) (time.Duration, error)
- func (l *DistributedLock) TryLock(ctx context.Context) (bool, error)
- func (l *DistributedLock) Unlock(ctx context.Context) error
- type ExpiringHandler
- func (h *ExpiringHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *ExpiringHandler) Close() error
- func (h *ExpiringHandler) Del(key []byte) error
- func (h *ExpiringHandler) Get(key []byte) ([]byte, error)
- func (h *ExpiringHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *ExpiringHandler) GetTTL(key []byte) (time.Duration, error)
- func (h *ExpiringHandler) Set(key, value []byte) error
- func (h *ExpiringHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
- func (h *ExpiringHandler) Stats() map[string]interface{}
- type Handler
- type HotKeyCache
- func (h *HotKeyCache[K, V]) Clear(ctx context.Context) error
- func (h *HotKeyCache[K, V]) Delete(ctx context.Context, key K) error
- func (h *HotKeyCache[K, V]) Exists(ctx context.Context, key K) (bool, error)
- func (h *HotKeyCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)
- func (h *HotKeyCache[K, V]) GetAll(ctx context.Context) (map[K]V, error)
- func (h *HotKeyCache[K, V]) GetStats(ctx context.Context) (*HotKeyStats, error)
- func (h *HotKeyCache[K, V]) Keys(ctx context.Context) ([]K, error)
- func (h *HotKeyCache[K, V]) LoadAll(ctx context.Context) (map[K]V, error)
- func (h *HotKeyCache[K, V]) Refresh(ctx context.Context) error
- func (h *HotKeyCache[K, V]) SaveToRedis(ctx context.Context) error
- func (h *HotKeyCache[K, V]) Set(ctx context.Context, key K, value V) error
- func (h *HotKeyCache[K, V]) SetAll(ctx context.Context, data map[K]V) error
- func (h *HotKeyCache[K, V]) Size(ctx context.Context) (int, error)
- func (h *HotKeyCache[K, V]) Stop()
- type HotKeyConfig
- type HotKeyManager
- func (m *HotKeyManager) GetAllStats(ctx context.Context) (map[string]*HotKeyStats, error)
- func (m *HotKeyManager) GetCache(name string) (interface{}, bool)
- func (m *HotKeyManager) RefreshAll(ctx context.Context) error
- func (m *HotKeyManager) RegisterCache(name string, cache interface{})
- func (m *HotKeyManager) StopAll()
- type HotKeyStats
- type IDGenerator
- func (g *IDGenerator) ForceResetSequence(ctx context.Context, timePrefix string) error
- func (g *IDGenerator) GenerateID(ctx context.Context) (string, error)
- func (g *IDGenerator) GenerateIDs(ctx context.Context, n int) ([]string, error)
- func (g *IDGenerator) GetCurrentSequence(ctx context.Context) (int64, error)
- func (g *IDGenerator) GetIDPrefix() string
- func (g *IDGenerator) GetIDSuffix() string
- func (g *IDGenerator) GetSeparator() string
- func (g *IDGenerator) GetSequenceByTime(ctx context.Context, timePrefix string) (int64, error)
- func (g *IDGenerator) ResetSequence(ctx context.Context, timePrefix string) error
- func (g *IDGenerator) WithExpire(d time.Duration) *IDGenerator
- func (g *IDGenerator) WithIDPrefix(prefix string) *IDGenerator
- func (g *IDGenerator) WithIDSuffix(suffix string) *IDGenerator
- func (g *IDGenerator) WithKeyPrefix(prefix string) *IDGenerator
- func (g *IDGenerator) WithSeparator(sep string) *IDGenerator
- func (g *IDGenerator) WithSequenceInitCallback(cb func() int64) *IDGenerator
- func (g *IDGenerator) WithSequenceLength(length int) *IDGenerator
- func (g *IDGenerator) WithSequenceStart(start int64) *IDGenerator
- func (g *IDGenerator) WithTimeFormat(format string) *IDGenerator
- type LRUHandler
- func (h *LRUHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *LRUHandler) Close() error
- func (h *LRUHandler) Del(key []byte) error
- func (h *LRUHandler) Get(key []byte) ([]byte, error)
- func (h *LRUHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *LRUHandler) GetTTL(key []byte) (time.Duration, error)
- func (h *LRUHandler) Set(key, value []byte) error
- func (h *LRUHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
- func (h *LRUHandler) Stats() map[string]interface{}
- type LRUOptimizedHandler
- func (h *LRUOptimizedHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *LRUOptimizedHandler) Close() error
- func (h *LRUOptimizedHandler) Del(key []byte) error
- func (h *LRUOptimizedHandler) Get(key []byte) ([]byte, error)
- func (h *LRUOptimizedHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *LRUOptimizedHandler) GetTTL(key []byte) (time.Duration, error)
- func (h *LRUOptimizedHandler) Set(key, value []byte) error
- func (h *LRUOptimizedHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
- func (h *LRUOptimizedHandler) Stats() map[string]interface{}
- type LockConfig
- type LockManager
- func (m *LockManager) CleanupExpiredLocks(ctx context.Context) error
- func (m *LockManager) GetAllLockStats(ctx context.Context) (map[string]*LockStats, error)
- func (m *LockManager) GetLock(key string) *DistributedLock
- func (m *LockManager) ReleaseAllLocks(ctx context.Context) error
- func (m *LockManager) ReleaseLock(ctx context.Context, key string) error
- type LockStats
- type MessageHandler
- type MultiLevelCache
- func (m *MultiLevelCache[T]) Clear(ctx context.Context) error
- func (m *MultiLevelCache[T]) Delete(ctx context.Context, key string) error
- func (m *MultiLevelCache[T]) Get(ctx context.Context, key string, loader func() (T, error)) (T, error)
- func (m *MultiLevelCache[T]) GetStats() map[string]int64
- func (m *MultiLevelCache[T]) InvalidateL1(key string)
- func (m *MultiLevelCache[T]) Set(ctx context.Context, key string, value T) error
- type MultiLevelConfig
- type PubSub
- func (p *PubSub) BroadcastMessage(ctx context.Context, channels []string, message interface{}) error
- func (p *PubSub) Close() error
- func (p *PubSub) GetChannels() []string
- func (p *PubSub) GetStats() *PubSubStats
- func (p *PubSub) GetSubscribers() int
- func (p *PubSub) Publish(ctx context.Context, channel string, message interface{}) error
- func (p *PubSub) RequestResponse(ctx context.Context, requestChannel, responseChannel string, ...) (string, error)
- func (p *PubSub) Subscribe(channels []string, handler MessageHandler) (*Subscriber, error)
- func (p *PubSub) SubscribePattern(patterns []string, handler MessageHandler) (*Subscriber, error)
- func (p *PubSub) Unsubscribe(channels ...string) error
- type PubSubConfig
- type PubSubStats
- type QueueConfig
- type QueueHandler
- func (q *QueueHandler) AcquireLock(ctx context.Context, queueName string, workerID string) (bool, error)
- func (q *QueueHandler) BatchDequeue(ctx context.Context, queueName string, queueType QueueType, count int) ([]*QueueItem, error)
- func (q *QueueHandler) Clear(ctx context.Context, queueName string, queueType QueueType) error
- func (q *QueueHandler) Contains(ctx context.Context, queueName string, queueType QueueType, itemID string) (bool, error)
- func (q *QueueHandler) Dequeue(ctx context.Context, queueName string, queueType QueueType) (*QueueItem, error)
- func (q *QueueHandler) DequeueNonBlocking(ctx context.Context, queueName string, queueType QueueType) (*QueueItem, error)
- func (q *QueueHandler) Enqueue(ctx context.Context, queueName string, queueType QueueType, item *QueueItem) error
- func (q *QueueHandler) GetFailedItems(ctx context.Context, queueName string, offset, limit int64) ([]*QueueItem, error)
- func (q *QueueHandler) GetStats(ctx context.Context, queueName string, queueType QueueType) (*QueueStats, error)
- func (q *QueueHandler) Length(ctx context.Context, queueName string, queueType QueueType) (int64, error)
- func (q *QueueHandler) Peek(ctx context.Context, queueName string, queueType QueueType, count int) ([]*QueueItem, error)
- func (q *QueueHandler) ReleaseLock(ctx context.Context, queueName string, workerID string) error
- func (q *QueueHandler) RetryFailed(ctx context.Context, queueName string, queueType QueueType, item *QueueItem) error
- type QueueItem
- type QueueStats
- type QueueType
- type RedisHandler
- func (h *RedisHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *RedisHandler) Close() error
- func (h *RedisHandler) Del(k []byte) error
- func (h *RedisHandler) Get(k []byte) ([]byte, error)
- func (h *RedisHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *RedisHandler) GetTTL(k []byte) (time.Duration, error)
- func (h *RedisHandler) Set(k, v []byte) error
- func (h *RedisHandler) SetWithTTL(k, v []byte, ttl time.Duration) error
- func (h *RedisHandler) Stats() map[string]interface{}
- func (h *RedisHandler) WithCtx(ctx context.Context) *RedisHandler
- type RistrettoConfig
- func (c *RistrettoConfig) EnableMetrics() *RistrettoConfig
- func (c *RistrettoConfig) SetBufferItems(bufferItems int64) *RistrettoConfig
- func (c *RistrettoConfig) SetCost(fn func(value []byte) int64) *RistrettoConfig
- func (c *RistrettoConfig) SetIgnoreInternalCost(ignore bool) *RistrettoConfig
- func (c *RistrettoConfig) SetKeyToHash(fn func(key []byte) (uint64, uint64)) *RistrettoConfig
- func (c *RistrettoConfig) SetMaxCost(maxCost int64) *RistrettoConfig
- func (c *RistrettoConfig) SetNumCounters(numCounters int64) *RistrettoConfig
- func (c *RistrettoConfig) SetOnEvict(fn func(item *ristretto.Item[[]byte])) *RistrettoConfig
- func (c *RistrettoConfig) SetOnExit(fn func(val []byte)) *RistrettoConfig
- func (c *RistrettoConfig) SetOnReject(fn func(item *ristretto.Item[[]byte])) *RistrettoConfig
- func (c *RistrettoConfig) SetShouldUpdate(fn func(cur, prev []byte) bool) *RistrettoConfig
- func (c *RistrettoConfig) SetTtlTickerDurationInSec(duration int64) *RistrettoConfig
- type RistrettoHandler
- func (h *RistrettoHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *RistrettoHandler) Close() error
- func (h *RistrettoHandler) Del(k []byte) error
- func (h *RistrettoHandler) Get(k []byte) ([]byte, error)
- func (h *RistrettoHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *RistrettoHandler) GetTTL(k []byte) (time.Duration, error)
- func (h *RistrettoHandler) Set(k, v []byte) error
- func (h *RistrettoHandler) SetWithTTL(k, v []byte, ttl time.Duration) error
- func (h *RistrettoHandler) Stats() map[string]interface{}
- type SQLDataLoader
- type ShardedHandler
- func (h *ShardedHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *ShardedHandler) Close() error
- func (h *ShardedHandler) Del(key []byte) error
- func (h *ShardedHandler) Get(key []byte) ([]byte, error)
- func (h *ShardedHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *ShardedHandler) GetTTL(key []byte) (time.Duration, error)
- func (h *ShardedHandler) Set(key, value []byte) error
- func (h *ShardedHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
- func (h *ShardedHandler) Stats() map[string]interface{}
- type SmartCache
- func (c *SmartCache) Close() error
- func (c *SmartCache) Delete(ctx context.Context, key string) error
- func (c *SmartCache) Get(ctx context.Context, key string) (interface{}, error)
- func (c *SmartCache) GetOrSet(ctx context.Context, key string, loader func() (interface{}, error)) (interface{}, error)
- func (c *SmartCache) Set(ctx context.Context, key string, value interface{}, ttl ...time.Duration) error
- func (c *SmartCache) Subscribe(ctx context.Context, event string, handler func(data interface{})) (*Subscriber, error)
- type Subscriber
- type TwoLevelHandler
- func (h *TwoLevelHandler) BatchGet(keys [][]byte) ([][]byte, []error)
- func (h *TwoLevelHandler) Close() error
- func (h *TwoLevelHandler) Del(key []byte) error
- func (h *TwoLevelHandler) Get(key []byte) ([]byte, error)
- func (h *TwoLevelHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
- func (h *TwoLevelHandler) GetTTL(key []byte) (time.Duration, error)
- func (h *TwoLevelHandler) Set(key, value []byte) error
- func (h *TwoLevelHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
- func (h *TwoLevelHandler) Stats() map[string]interface{}
- type TypedMessageHandler
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound 表示在缓存中找不到请求的键 // 当尝试获取一个不存在的缓存项时返回此错误 ErrNotFound = errors.New("key not found in cache") // ErrDataWrite 表示写入数据时发生错误 // 当向缓存存储数据失败时返回此错误 ErrDataWrite = errors.New("failed to write data to cache") // ErrDataRead 表示读取数据时发生错误 // 当从缓存读取数据失败时返回此错误 ErrDataRead = errors.New("failed to read data from cache") // ErrClosed 表示缓存已关闭 // 当尝试在已关闭的缓存实例上执行操作时返回此错误 ErrClosed = errors.New("cache is closed") // ErrInvalidKey 表示使用了无效的键 // 当传入的缓存键为空或格式不正确时返回此错误 ErrInvalidKey = errors.New("invalid cache key") // ErrInvalidValue 表示使用了无效的值 // 当传入的缓存值为nil或格式不正确时返回此错误 ErrInvalidValue = errors.New("invalid cache value") // ErrInvalidTTL 表示使用了无效的 TTL 值 // 当传入的过期时间为负数或其他无效值时返回此错误 ErrInvalidTTL = errors.New("invalid TTL value") // ErrCapacityExceeded 表示超出了缓存容量限制 // 当缓存已达到最大容量限制无法存储更多数据时返回此错误 ErrCapacityExceeded = errors.New("cache capacity exceeded") // ErrNotInitialized 表示缓存未正确初始化 // 当尝试使用未初始化的缓存实例时返回此错误 ErrNotInitialized = errors.New("cache not properly initialized") // 当底层存储服务(如Redis、Memcached等)连接失败或不可达时返回此错误 ErrUnavailable = errors.New("cache service unavailable") // ErrTimeout 表示操作超时 // 当缓存操作执行时间超过设定的超时时间时返回此错误 ErrTimeout = errors.New("cache operation timed out") )
Functions ¶
func LockWithRetry ¶ added in v0.1.2
func LockWithRetry(ctx context.Context, client *redis.Client, key string, config LockConfig, fn func() error) error
LockWithRetry 带重试的锁获取工具函数
func MutexLock ¶ added in v0.1.2
func MutexLock(ctx context.Context, client *redis.Client, key string, ttl time.Duration, fn func() error) error
MutexLock 互斥锁工具函数,确保同时只有一个操作在执行
func NewRedisOptions ¶ added in v0.1.2
NewRedisOptions 创建推荐的Redis配置 这个函数设置了一些推荐的默认值以避免常见的警告和问题
func PublishJSON ¶ added in v0.1.2
PublishJSON 发布JSON消息(泛型版本)
func SimplePublish ¶ added in v0.1.2
SimplePublish 简单发布消息
func ValidateBasicOp ¶
ValidateBasicOp 验证基本操作的参数(检查键、缓存状态)
func ValidateInitialized ¶
ValidateInitialized 验证缓存是否已初始化
func ValidateWriteOp ¶
ValidateWriteOp 验证写操作的参数(检查键、值、缓存状态)
func ValidateWriteWithTTLOp ¶
ValidateWriteWithTTLOp 验证带 TTL 的写操作参数
Types ¶
type AdvancedCache ¶ added in v0.1.2
type AdvancedCache[T any] struct { // contains filtered or unexported fields }
AdvancedCache 高级缓存包装器
func NewAdvancedCache ¶ added in v0.1.2
func NewAdvancedCache[T any](client *redis.Client, config AdvancedCacheConfig) *AdvancedCache[T]
NewAdvancedCache 创建高级缓存
func (*AdvancedCache[T]) BatchSet ¶ added in v0.1.2
func (c *AdvancedCache[T]) BatchSet(ctx context.Context, items map[string]T, ttl ...time.Duration) error
BatchSet 批量设置
func (*AdvancedCache[T]) Clear ¶ added in v0.1.2
func (c *AdvancedCache[T]) Clear(ctx context.Context, pattern string) error
Clear 清空指定模式的所有缓存
func (*AdvancedCache[T]) Close ¶ added in v0.1.2
func (c *AdvancedCache[T]) Close() error
Close 关闭缓存
func (*AdvancedCache[T]) Delete ¶ added in v0.1.2
func (c *AdvancedCache[T]) Delete(ctx context.Context, keys ...string) error
Delete 删除缓存
func (*AdvancedCache[T]) GetHotKeyManager ¶ added in v0.1.2
func (c *AdvancedCache[T]) GetHotKeyManager() *HotKeyManager
GetHotKeyManager 获取热key管理器
func (*AdvancedCache[T]) GetLockManager ¶ added in v0.1.2
func (c *AdvancedCache[T]) GetLockManager() *LockManager
GetLockManager 获取锁管理器
func (*AdvancedCache[T]) GetMetrics ¶ added in v0.1.2
func (c *AdvancedCache[T]) GetMetrics() *CacheMetrics
GetMetrics 获取缓存指标
func (*AdvancedCache[T]) GetOrSet ¶ added in v0.1.2
func (c *AdvancedCache[T]) GetOrSet(ctx context.Context, key string, fn func() (T, error), ttl ...time.Duration) (T, error)
GetOrSet 获取或设置缓存(如果不存在则设置)
func (*AdvancedCache[T]) GetQueue ¶ added in v0.1.2
func (c *AdvancedCache[T]) GetQueue() *QueueHandler
GetQueue 获取队列处理器
func (*AdvancedCache[T]) Ping ¶ added in v0.1.2
func (c *AdvancedCache[T]) Ping(ctx context.Context) error
Ping 测试连接
func (*AdvancedCache[T]) ResetMetrics ¶ added in v0.1.2
func (c *AdvancedCache[T]) ResetMetrics()
ResetMetrics 重置缓存指标
func (*AdvancedCache[T]) Set ¶ added in v0.1.2
func (c *AdvancedCache[T]) Set(ctx context.Context, key string, value T, ttl ...time.Duration) error
Set 设置缓存
func (*AdvancedCache[T]) Wrap ¶ added in v0.1.2
func (c *AdvancedCache[T]) Wrap(key string, fn CacheWrapperFunc[T], ttl ...time.Duration) CacheWrapperFunc[T]
Wrap 包装函数以添加缓存功能
type AdvancedCacheConfig ¶ added in v0.1.2
type AdvancedCacheConfig struct {
Compression CompressionType // 压缩类型
MinSizeForCompress int // 启用压缩的最小大小(字节)
DefaultTTL time.Duration // 默认TTL
Namespace string // 命名空间
EnableMetrics bool // 是否启用指标统计
}
AdvancedCacheConfig 高级缓存配置
type CacheAsideOperation ¶ added in v0.1.7
type CacheAsideOperation[T any] struct { // contains filtered or unexported fields }
CacheAsideOperation 旁路缓存操作
func (*CacheAsideOperation[T]) Read ¶ added in v0.1.7
func (op *CacheAsideOperation[T]) Read() (T, error)
Read 读取数据
func (*CacheAsideOperation[T]) Write ¶ added in v0.1.7
func (op *CacheAsideOperation[T]) Write(value T) error
Write 写入数据(延迟双删模式)
type CacheBuilder ¶ added in v0.1.7
type CacheBuilder struct {
// contains filtered or unexported fields
}
CacheBuilder 缓存构建器
func NewCacheBuilder ¶ added in v0.1.7
func NewCacheBuilder(redisClient redis.UniversalClient, namespace string) *CacheBuilder
NewCacheBuilder 创建缓存构建器
func (*CacheBuilder) Build ¶ added in v0.1.7
func (b *CacheBuilder) Build() *SmartCache
Build 构建缓存实例
func (*CacheBuilder) OnError ¶ added in v0.1.7
func (b *CacheBuilder) OnError(fn func(ctx context.Context, err error)) *CacheBuilder
OnError 设置错误回调
func (*CacheBuilder) OnMiss ¶ added in v0.1.7
func (b *CacheBuilder) OnMiss(fn func(ctx context.Context, key string) (interface{}, error)) *CacheBuilder
OnMiss 设置缓存未命中回调(数据加载器)
func (*CacheBuilder) OnSet ¶ added in v0.1.7
func (b *CacheBuilder) OnSet(fn func(ctx context.Context, key string, value interface{})) *CacheBuilder
OnSet 设置缓存设置后回调
func (*CacheBuilder) WithCompression ¶ added in v0.1.7
func (b *CacheBuilder) WithCompression(compType CompressionType) *CacheBuilder
WithCompression 启用压缩
func (*CacheBuilder) WithHotKey ¶ added in v0.1.7
func (b *CacheBuilder) WithHotKey() *CacheBuilder
WithHotKey 启用热key保护
func (*CacheBuilder) WithKeyPattern ¶ added in v0.1.7
func (b *CacheBuilder) WithKeyPattern(pattern string) *CacheBuilder
WithKeyPattern 设置key模板
func (*CacheBuilder) WithLock ¶ added in v0.1.7
func (b *CacheBuilder) WithLock(timeout time.Duration) *CacheBuilder
WithLock 启用分布式锁
func (*CacheBuilder) WithPubSub ¶ added in v0.1.7
func (b *CacheBuilder) WithPubSub() *CacheBuilder
WithPubSub 启用发布订阅
func (*CacheBuilder) WithRefreshThreshold ¶ added in v0.1.7
func (b *CacheBuilder) WithRefreshThreshold(threshold float64) *CacheBuilder
WithRefreshThreshold 设置自动刷新阈值
func (*CacheBuilder) WithTTL ¶ added in v0.1.7
func (b *CacheBuilder) WithTTL(ttl time.Duration) *CacheBuilder
WithTTL 设置默认过期时间
type CacheFunc ¶ added in v0.1.3
CacheFunc 是一个函数类型,用于表示返回数据和错误的数据加载函数。
泛型参数:
T: 数据加载函数返回的数据类型,可以是任意可序列化为JSON的类型
参数:
ctx: 上下文,用于控制超时和取消
返回值:
T: 加载的数据 error: 加载过程中可能出现的错误
func CacheWrapper ¶ added in v0.1.3
func CacheWrapper[T any](client *redis.Client, key string, cacheFunc CacheFunc[T], expiration time.Duration, opts ...CacheOption) CacheFunc[T]
CacheWrapper 是一个高阶函数,用于为数据加载函数添加Redis缓存功能。
该函数实现了以下核心特性:
- 缓存查询:首先尝试从Redis获取缓存数据
- 数据压缩:使用Zlib算法压缩缓存数据,减少内存使用
- 延迟双删:实现延迟双删策略,防止并发写入导致的缓存不一致
- 错误处理:区分Redis连接错误和键不存在错误,优雅降级
缓存流程:
- 尝试从Redis获取缓存数据
- 如果缓存存在且有效,解压缩并反序列化返回
- 如果缓存不存在或无效,执行原始数据加载函数
- 将加载的数据序列化、压缩后存储到Redis
- 执行延迟双删策略确保缓存一致性
延迟双删策略:
- 第一次删除:在设置新缓存前删除旧缓存
- 设置缓存:存储新的缓存数据
- 延迟删除:100ms后再次删除缓存并重新设置,防止并发问题
泛型参数:
T: 缓存数据的类型,必须支持JSON序列化
参数:
client: Redis客户端实例 key: 缓存键名,建议使用有意义的命名规范 cacheFunc: 数据加载函数,当缓存不存在时调用 expiration: 缓存过期时间
返回值:
返回一个缓存包装后的数据加载函数,该函数具有相同的签名但增加了缓存功能
使用示例:
创建用户数据加载器
userLoader := func(ctx context.Context) (*User, error) {
return getUserFromDB(ctx, userID)
}
包装为缓存加载器
cachedLoader := CacheWrapper(client, "user:123", userLoader, time.Hour)
使用缓存加载器
user, err := cachedLoader(ctx)
注意事项:
- 确保数据类型T支持JSON序列化
- 缓存键名应该具有唯一性和可读性
- 合理设置过期时间以平衡性能和数据一致性
- 大对象缓存会消耗更多内存,即使有压缩
- 可通过 WithForceRefresh(true) 强制刷新缓存
type CacheMetrics ¶ added in v0.1.2
type CacheMetrics struct {
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
Sets int64 `json:"sets"`
Deletes int64 `json:"deletes"`
Compressions int64 `json:"compressions"`
Decompressions int64 `json:"decompressions"`
TotalSize int64 `json:"total_size"`
}
CacheMetrics 缓存指标
type CacheOption ¶ added in v0.1.4
type CacheOption func(*CacheOptions)
CacheOption 缓存选项函数类型
func Combine ¶ added in v0.1.5
func Combine(opts ...CacheOption) CacheOption
Combine 组合多个选项为一个选项
参数:
opts: 要组合的选项列表
使用场景:
- 将多个相关选项组合成一个预设
- 创建可重用的选项组合
- 简化选项传递
示例:
vipPreset := Combine(
WithTTL(time.Hour * 24),
WithRetry(3),
WithAsyncUpdate(),
)
func Match ¶ added in v0.1.5
func Match(cases []Case, defaultOpt ...CacheOption) CacheOption
Match 多条件匹配选项构建器 - 类似 switch-case
参数:
cases: 条件-选项对的切片 defaultOpt: 所有条件都不满足时的默认选项(可选)
使用场景:
- 多个互斥条件的选项选择
- 替代复杂的 if-else-if 链
- 提高代码可读性
示例:
Match([]Case{
{Condition: level == "VIP", Opt: WithTTL(time.Hour * 24)},
{Condition: level == "Premium", Opt: WithTTL(time.Hour * 12)},
}, WithTTL(time.Hour))
func When ¶ added in v0.1.5
func When(condition bool, opt CacheOption) CacheOption
When 条件选项构建器 - 当条件为 true 时应用选项
参数:
condition: 条件表达式 opt: 当条件为 true 时应用的选项
使用场景:
- 简化条件选项的构建代码
- 提高代码可读性
- 函数式编程风格
示例:
When(isVIP, WithTTL(time.Hour * 24)) When(needRefresh, WithForceRefresh(true))
func WhenThen ¶ added in v0.1.5
func WhenThen(condition bool, thenOpt, elseOpt CacheOption) CacheOption
WhenThen 条件选项构建器 - 根据条件选择不同的选项
参数:
condition: 条件表达式 thenOpt: 当条件为 true 时应用的选项 elseOpt: 当条件为 false 时应用的选项
使用场景:
- 二选一的选项场景
- 简化 if-else 逻辑
- 函数式编程风格
示例:
WhenThen(isVIP, WithTTL(time.Hour * 24), WithTTL(time.Hour))
func WithAsyncUpdate ¶ added in v0.1.5
func WithAsyncUpdate() CacheOption
WithAsyncUpdate 使用异步方式更新缓存
使用场景:
- 非关键数据,允许短暂的数据延迟
- 高并发场景,减少阻塞
- 缓存更新耗时较长的情况
func WithForceRefresh ¶ added in v0.1.4
func WithForceRefresh(force bool) CacheOption
WithForceRefresh 设置是否强制刷新缓存
参数:
force: true 表示强制从数据源加载,false 表示优先使用缓存
使用场景:
- 管理员操作需要最新数据
- 定时任务刷新缓存
- 数据变更后立即更新缓存
func WithJitter ¶ added in v0.1.8
func WithJitter(percent float64) CacheOption
WithJitter 设置 TTL 随机抖动百分比,避免缓存雪崩
参数:
percent: 抖动百分比(0-1),例如 0.005 表示 ±0.5% 的随机抖动
使用场景:
- 大量缓存同时创建,避免同时失效
- 防止缓存雪崩
- 分散缓存失效时间
示例:
WithJitter(0.005) // ±0.5% 抖动,1小时缓存会在 59.7-60.3 分钟之间随机失效 WithJitter(0.01) // ±1% 抖动,1小时缓存会在 59.4-60.6 分钟之间随机失效 WithJitter(0.05) // ±5% 抖动,1小时缓存会在 57-63 分钟之间随机失效
func WithRetry ¶ added in v0.1.5
func WithRetry(times int) CacheOption
WithRetry 设置 Redis 操作失败时重试
参数:
times: 重试次数(建议不超过 3 次)
使用场景:
- Redis 网络不稳定
- 关键数据必须缓存成功
- 提高缓存可靠性
func WithTTL ¶ added in v0.1.5
func WithTTL(ttl time.Duration) CacheOption
WithTTL 覆盖默认的缓存过期时间
参数:
ttl: 自定义的缓存过期时间
使用场景:
- 动态调整缓存时长
- 不同条件下使用不同的 TTL
- VIP 用户使用更长的缓存时间
func WithoutCompression ¶ added in v0.1.5
func WithoutCompression() CacheOption
WithoutCompression 跳过数据压缩
使用场景:
- 数据量很小(如布尔值、小字符串)
- 数据已经压缩过(如图片、视频链接)
- 需要极致性能,压缩开销大于收益
type CacheOptions ¶ added in v0.1.4
type CacheOptions struct {
ForceRefresh bool // 是否强制刷新缓存(清除缓存重新获取)
TTLOverride *time.Duration // 覆盖默认 TTL(为 nil 时使用默认值)
SkipCompress bool // 跳过压缩(用于小数据或已压缩的数据)
UseAsync bool // 使用异步更新缓存(适用于非关键数据)
RetryOnError bool // Redis 错误时重试(默认不重试)
RetryTimes int // 重试次数(默认 0)
JitterPercent *float64 // TTL 随机抖动百分比(0-1,nil 时使用默认 0.005 即 ±0.5%)
}
CacheOptions 缓存选项配置
type CachePattern ¶ added in v0.1.7
type CachePattern[T any] struct { // contains filtered or unexported fields }
CachePattern 缓存模式封装(生产级别)
func NewCachePattern ¶ added in v0.1.7
func NewCachePattern[T any](cache *MultiLevelCache[T]) *CachePattern[T]
NewCachePattern 创建缓存模式
func (*CachePattern[T]) CacheAside ¶ added in v0.1.7
func (p *CachePattern[T]) CacheAside( ctx context.Context, key string, dbLoader func() (T, error), dbWriter func(T) error, ) *CacheAsideOperation[T]
CacheAside 旁路缓存模式(Cache-Aside) 读:先读缓存,未命中则读DB并写入缓存 写:先写DB,再删除缓存(延迟双删)
func (*CachePattern[T]) ReadThrough ¶ added in v0.1.7
func (p *CachePattern[T]) ReadThrough(ctx context.Context, key string, dbLoader func() (T, error)) (T, error)
ReadThrough 穿透读缓存模式
func (*CachePattern[T]) WriteBehind ¶ added in v0.1.7
func (p *CachePattern[T]) WriteBehind(ctx context.Context, key string, value T, dbWriter func(T) error) error
WriteBehind 异步写缓存模式(Write-Behind/Write-Back)
func (*CachePattern[T]) WriteThrough ¶ added in v0.1.7
func (p *CachePattern[T]) WriteThrough(ctx context.Context, key string, value T, dbWriter func(T) error) error
WriteThrough 穿透写缓存模式
type CacheStrategy ¶ added in v0.1.7
type CacheStrategy struct {
// 基础配置
Namespace string
KeyPattern string // key模板,如: "user:{user_id}"
DefaultTTL time.Duration // 默认过期时间
Compression CompressionType
// 高级功能
EnableHotKey bool // 启用热key保护
EnableLock bool // 启用分布式锁
EnablePubSub bool // 启用发布订阅
LockTimeout time.Duration // 锁超时时间
RefreshThreshold float64 // 刷新阈值(0-1),剩余TTL低于此值时自动刷新
// 回调函数
OnCacheMiss func(ctx context.Context, key string) (interface{}, error) // 缓存未命中时的回调
OnCacheSet func(ctx context.Context, key string, value interface{}) // 缓存设置后的回调
OnError func(ctx context.Context, err error) // 错误回调
}
CacheStrategy 缓存策略
type CacheWrapperFunc ¶ added in v0.1.2
CacheWrapper 缓存包装器函数类型
type Case ¶ added in v0.1.5
type Case struct {
Condition bool // 条件
Opt CacheOption // 选项
}
Case 条件-选项对
type Client ¶ added in v0.1.2
type Client struct {
// contains filtered or unexported fields
}
Client 是支持 context 的缓存客户端
func NewClient ¶ added in v0.1.2
func NewClient(ctx context.Context, cfg *ClientConfig) (*Client, error)
NewClient 根据配置创建带 context 能力的缓存客户端
func NewExpiringClient ¶ added in v0.1.2
NewExpiringClient 创建过期缓存客户端的便利函数
func NewLRUClient ¶ added in v0.1.2
NewLRUClient 创建 LRU 缓存客户端的便利函数
func NewLRUOptimizedClient ¶ added in v0.1.2
NewLRUOptimizedClient 创建优化版本 LRU 缓存客户端的便利函数
func NewRedisClient ¶ added in v0.1.2
NewRedisClient 创建 Redis 缓存客户端的便利函数
func NewRistrettoClient ¶ added in v0.1.2
func NewRistrettoClient(ctx context.Context, config *RistrettoConfig) (*Client, error)
NewRistrettoClient 创建 Ristretto 缓存客户端的便利函数
func (*Client) GetConfig ¶ added in v0.1.2
func (c *Client) GetConfig() ClientConfig
GetConfig 返回客户端配置(只读)
func (*Client) GetOrCompute ¶ added in v0.1.2
func (c *Client) GetOrCompute(ctx context.Context, key []byte, ttl time.Duration, loader func(context.Context) ([]byte, error)) ([]byte, error)
GetOrCompute 获取或计算缓存值(带去重)
func (*Client) SetWithTTL ¶ added in v0.1.2
SetWithTTL 设置带TTL的缓存值
type ClientConfig ¶ added in v0.1.2
type ClientConfig struct {
Type CacheType
Capacity int // for lru/expiring/ristretto
CleanupInterval time.Duration // for expiring cache
RedisConfig *redis.Options // for redis
RistrettoConfig *RistrettoConfig // for ristretto
}
ClientConfig 用于统一配置入口
type CompressionType ¶ added in v0.1.2
type CompressionType string
CompressionType 压缩类型
const ( CompressionNone CompressionType = "none" CompressionGzip CompressionType = "gzip" )
type ContextHandler ¶ added in v0.1.2
type ContextHandler interface {
// Set 设置缓存键值对(支持context)
// ctx: 上下文,用于控制超时和取消操作
// key: 缓存键,不能为空
// value: 缓存值,可以为任意字节数组
// 返回值: 设置成功返回nil,失败返回相应错误
Set(ctx context.Context, key, value []byte) error
// SetWithTTL 设置带有过期时间的缓存键值对(支持context)
// ctx: 上下文,用于控制超时和取消操作
// key: 缓存键,不能为空
// value: 缓存值,可以为任意字节数组
// ttl: 过期时间,必须为正数
// 返回值: 设置成功返回nil,失败返回相应错误
SetWithTTL(ctx context.Context, key, value []byte, ttl time.Duration) error
// Get 根据键获取缓存值(支持context)
// ctx: 上下文,用于控制超时和取消操作
// key: 要查询的缓存键
// 返回值: 找到返回值和nil错误,未找到返回nil和ErrNotFound错误
Get(ctx context.Context, key []byte) ([]byte, error)
// GetTTL 获取指定键的剩余过期时间(支持context)
// ctx: 上下文,用于控制超时和取消操作
// key: 要查询的缓存键
// 返回值: 剩余过期时间和错误信息,如果键不存在返回0和ErrNotFound
GetTTL(ctx context.Context, key []byte) (time.Duration, error)
// Del 删除指定的缓存键(支持context)
// ctx: 上下文,用于控制超时和取消操作
// key: 要删除的缓存键
// 返回值: 删除成功返回nil,失败返回相应错误
Del(ctx context.Context, key []byte) error
// GetOrCompute 获取缓存值,如果不存在则通过loader函数计算并存储
// 这是一个常用的缓存模式,可以避免缓存穿透问题
// ctx: 上下文,用于控制超时和取消操作
// key: 缓存键
// ttl: 计算出的值的过期时间
// loader: 当缓存不存在时用于计算值的函数
// 返回值: 缓存值和错误信息
GetOrCompute(ctx context.Context, key []byte, ttl time.Duration, loader func(context.Context) ([]byte, error)) ([]byte, error)
// BatchGet 批量获取多个键的值(支持context)
// ctx: 上下文,用于控制超时和取消操作
// keys: 要查询的缓存键数组
// 返回值: 对应的值数组和错误数组,索引一一对应
BatchGet(ctx context.Context, keys [][]byte) ([][]byte, []error)
// Stats 获取缓存统计信息(支持context)
// ctx: 上下文,用于控制超时和取消操作
// 返回值: 包含缓存统计数据的map,如命中率、大小、元素数量等
Stats(ctx context.Context) map[string]interface{}
// Close 关闭缓存实例并释放资源
// 注意:Close操作通常不需要context,因为它是清理操作
// 返回值: 关闭成功返回nil,失败返回相应错误
Close() error
}
ContextHandler 是支持 context 的缓存操作接口 继承了Handler的所有功能,并在每个操作中添加了context支持 context可以用于超时控制、取消操作和传递请求相关的元数据
type CtxCache ¶
type CtxCache struct {
// contains filtered or unexported fields
}
CtxCache 是一个基于 context 的缓存封装,包装已有的 Handler 它提供支持 context 取消的 GetOrCompute(带 loader)以及并发去重(singleflight)
func FromContext ¶
FromContext 从 ctx 中读取 CtxCache(若不存在返回 nil)
func (*CtxCache) GetOrCompute ¶
func (c *CtxCache) GetOrCompute(ctx context.Context, key []byte, ttl time.Duration, loader func(context.Context) ([]byte, error)) ([]byte, error)
GetOrCompute:先尝试从缓存读取;若未命中,则使用 singleflight 保证并发时只会执行一次 loader loader 应该尊重传入的 ctx(以便在 ctx 取消时尽早停止) - key: 缓存键(字节切片) - ttl: 保存到缓存的 TTL(<=0 表示不设置 TTL) - loader: 计算值的函数,接收同一个 ctx
func (*CtxCache) SetWithTTL ¶
SetWithTTL 写入缓存并设置 TTL
type DataLoader ¶ added in v0.1.2
type DataLoader[K comparable, V any] interface { Load(ctx context.Context) (map[K]V, error) }
DataLoader 数据加载器接口
type DistributedLock ¶ added in v0.1.2
type DistributedLock struct {
// contains filtered or unexported fields
}
DistributedLock 分布式锁
func NewDistributedLock ¶ added in v0.1.2
func NewDistributedLock(client *redis.Client, key string, config LockConfig) *DistributedLock
NewDistributedLock 创建分布式锁
func (*DistributedLock) GetStats ¶ added in v0.1.2
func (l *DistributedLock) GetStats(ctx context.Context) (*LockStats, error)
func (*DistributedLock) IsLocked ¶ added in v0.1.2
func (l *DistributedLock) IsLocked(ctx context.Context) (bool, error)
IsLocked 检查锁是否仍然有效
func (*DistributedLock) Lock ¶ added in v0.1.2
func (l *DistributedLock) Lock(ctx context.Context) error
Lock 获取锁(阻塞)
func (*DistributedLock) LockWithTimeout ¶ added in v0.1.2
LockWithTimeout 带超时的获取锁
type ExpiringHandler ¶
type ExpiringHandler struct {
// contains filtered or unexported fields
}
ExpiringHandler 是一个简单的基于 map 的线程安全内存缓存,支持 TTL 和后台清理 它实现了 Handler 接口
func NewExpiringHandler ¶
func NewExpiringHandler(cleanupInterval time.Duration) *ExpiringHandler
NewExpiringHandler 创建一个新的 ExpiringHandler,cleanupInterval 控制后台清理频率(为0则使用1s)
func (*ExpiringHandler) BatchGet ¶ added in v0.1.2
func (h *ExpiringHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取多个键的值
func (*ExpiringHandler) Get ¶
func (h *ExpiringHandler) Get(key []byte) ([]byte, error)
Get 读取值,如果不存在或已过期返回 ErrNotFound
func (*ExpiringHandler) GetOrCompute ¶ added in v0.1.2
func (h *ExpiringHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置
func (*ExpiringHandler) GetTTL ¶
func (h *ExpiringHandler) GetTTL(key []byte) (time.Duration, error)
GetTTL 返回剩余 TTL(0 表示无 TTL),找不到返回 ErrNotFound
func (*ExpiringHandler) Set ¶
func (h *ExpiringHandler) Set(key, value []byte) error
Set 将值写入缓存(无 TTL)
func (*ExpiringHandler) SetWithTTL ¶
func (h *ExpiringHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
SetWithTTL 写入值并设置 TTL(ttl<=0 表示不过期)
func (*ExpiringHandler) Stats ¶ added in v0.1.2
func (h *ExpiringHandler) Stats() map[string]interface{}
Stats 返回缓存统计信息
type Handler ¶
type Handler interface {
// Set 设置缓存键值对
// key: 缓存键,不能为空
// value: 缓存值,可以为任意字节数组
// 返回值: 设置成功返回nil,失败返回相应错误
Set([]byte, []byte) error
// SetWithTTL 设置带有过期时间的缓存键值对
// key: 缓存键,不能为空
// value: 缓存值,可以为任意字节数组
// ttl: 过期时间,必须为正数
// 返回值: 设置成功返回nil,失败返回相应错误
SetWithTTL([]byte, []byte, time.Duration) error
// Get 根据键获取缓存值
// key: 要查询的缓存键
// 返回值: 找到返回值和nil错误,未找到返回nil和ErrNotFound错误
Get([]byte) ([]byte, error)
// GetTTL 获取指定键的剩余过期时间
// key: 要查询的缓存键
// 返回值: 剩余过期时间和错误信息,如果键不存在返回0和ErrNotFound
GetTTL([]byte) (time.Duration, error)
// Del 删除指定的缓存键
// key: 要删除的缓存键
// 返回值: 删除成功返回nil,失败返回相应错误
Del([]byte) error
// BatchGet 批量获取多个键的值
// keys: 要查询的缓存键数组
// 返回值: 对应的值数组和错误数组,索引一一对应
BatchGet([][]byte) ([][]byte, []error)
// Stats 获取缓存统计信息
// 返回值: 包含缓存统计数据的map,如命中率、大小、元素数量等
Stats() map[string]interface{}
// Close 关闭缓存实例并释放资源
// 返回值: 关闭成功返回nil,失败返回相应错误
Close() error
}
Handler 是缓存操作的基础接口 提供了最基本的缓存操作方法,包括增删改查和统计功能 这是一个同步接口,不支持context控制
func NewRedisHandler ¶
NewRedisHandler 创建新的 RedisHandler
type HotKeyCache ¶ added in v0.1.2
type HotKeyCache[K comparable, V any] struct { // contains filtered or unexported fields }
HotKeyCache 热key缓存
func NewHotKeyCache ¶ added in v0.1.2
func NewHotKeyCache[K comparable, V any]( client *redis.Client, keyName string, loader DataLoader[K, V], config HotKeyConfig, ) *HotKeyCache[K, V]
NewHotKeyCache 创建热key缓存
func (*HotKeyCache[K, V]) Clear ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Clear(ctx context.Context) error
Clear 清空缓存
func (*HotKeyCache[K, V]) Delete ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Delete(ctx context.Context, key K) error
Delete 删除单个键
func (*HotKeyCache[K, V]) Exists ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Exists(ctx context.Context, key K) (bool, error)
Exists 检查键是否存在
func (*HotKeyCache[K, V]) Get ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)
Get 获取单个值
func (*HotKeyCache[K, V]) GetAll ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) GetAll(ctx context.Context) (map[K]V, error)
GetAll 获取所有值
func (*HotKeyCache[K, V]) GetStats ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) GetStats(ctx context.Context) (*HotKeyStats, error)
func (*HotKeyCache[K, V]) Keys ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Keys(ctx context.Context) ([]K, error)
Keys 获取所有键
func (*HotKeyCache[K, V]) LoadAll ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) LoadAll(ctx context.Context) (map[K]V, error)
LoadAll 从Redis或数据源加载所有数据
func (*HotKeyCache[K, V]) Refresh ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Refresh(ctx context.Context) error
Refresh 手动刷新缓存
func (*HotKeyCache[K, V]) SaveToRedis ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) SaveToRedis(ctx context.Context) error
SaveToRedis 保存到Redis
func (*HotKeyCache[K, V]) Set ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) Set(ctx context.Context, key K, value V) error
Set 设置单个值
func (*HotKeyCache[K, V]) SetAll ¶ added in v0.1.2
func (h *HotKeyCache[K, V]) SetAll(ctx context.Context, data map[K]V) error
SetAll 设置所有值
type HotKeyConfig ¶ added in v0.1.2
type HotKeyConfig struct {
DefaultTTL time.Duration // 默认TTL
RefreshInterval time.Duration // 刷新间隔
EnableAutoRefresh bool // 是否启用自动刷新
Namespace string // 命名空间
}
HotKeyConfig 热key配置
type HotKeyManager ¶ added in v0.1.2
type HotKeyManager struct {
// contains filtered or unexported fields
}
HotKeyManager 热key管理器
func NewHotKeyManager ¶ added in v0.1.2
func NewHotKeyManager(redisClient redis.UniversalClient, config ...HotKeyConfig) *HotKeyManager
NewHotKeyManager 创建热key管理器
func (*HotKeyManager) GetAllStats ¶ added in v0.1.2
func (m *HotKeyManager) GetAllStats(ctx context.Context) (map[string]*HotKeyStats, error)
GetAllStats 获取所有缓存统计
func (*HotKeyManager) GetCache ¶ added in v0.1.2
func (m *HotKeyManager) GetCache(name string) (interface{}, bool)
GetCache 获取缓存
func (*HotKeyManager) RefreshAll ¶ added in v0.1.2
func (m *HotKeyManager) RefreshAll(ctx context.Context) error
RefreshAll 刷新所有缓存
func (*HotKeyManager) RegisterCache ¶ added in v0.1.2
func (m *HotKeyManager) RegisterCache(name string, cache interface{})
RegisterCache 注册缓存
type HotKeyStats ¶ added in v0.1.2
type HotKeyStats struct {
KeyName string `json:"key_name"`
LocalCacheSize int `json:"local_cache_size"`
LastRefreshTime time.Time `json:"last_refresh_time"`
TTL int64 `json:"ttl_seconds"`
}
GetStats 获取统计信息
type IDGenerator ¶ added in v0.1.5
type IDGenerator struct {
OnSequenceInit func() int64 // key不存在时动态获取起始值
// contains filtered or unexported fields
}
IDGenerator 通用ID生成器
func NewIDGenerator ¶ added in v0.1.5
func NewIDGenerator(redisClient redis.UniversalClient) *IDGenerator
NewIDGenerator 创建ID生成器实例
func (*IDGenerator) ForceResetSequence ¶ added in v0.1.7
func (g *IDGenerator) ForceResetSequence(ctx context.Context, timePrefix string) error
ForceResetSequence 强制重置指定时间的序列号(仅用于测试或特殊场景) 警告:此方法会删除已有序列号,可能导致ID重复,生产环境慎用
func (*IDGenerator) GenerateID ¶ added in v0.1.5
func (g *IDGenerator) GenerateID(ctx context.Context) (string, error)
GenerateID 生成一个ID
func (*IDGenerator) GenerateIDs ¶ added in v0.1.5
GenerateIDs 批量生成ID(Lua脚本实现,原子高效)
func (*IDGenerator) GetCurrentSequence ¶ added in v0.1.5
func (g *IDGenerator) GetCurrentSequence(ctx context.Context) (int64, error)
GetCurrentSequence 获取当前时间的序列号(不增加)
func (*IDGenerator) GetIDPrefix ¶ added in v0.1.5
func (g *IDGenerator) GetIDPrefix() string
Getter方法,便于测试
func (*IDGenerator) GetIDSuffix ¶ added in v0.1.5
func (g *IDGenerator) GetIDSuffix() string
func (*IDGenerator) GetSeparator ¶ added in v0.1.5
func (g *IDGenerator) GetSeparator() string
func (*IDGenerator) GetSequenceByTime ¶ added in v0.1.5
GetSequenceByTime 获取指定时间段的序列号(不增加)
func (*IDGenerator) ResetSequence ¶ added in v0.1.5
func (g *IDGenerator) ResetSequence(ctx context.Context, timePrefix string) error
ResetSequence 仅在 key 不存在时初始化序列号,已存在则不做任何操作 这样可以避免在分布式环境下误删已有序列号导致ID重复
func (*IDGenerator) WithExpire ¶ added in v0.1.7
func (g *IDGenerator) WithExpire(d time.Duration) *IDGenerator
WithExpire 设置序列号过期时间
func (*IDGenerator) WithIDPrefix ¶ added in v0.1.7
func (g *IDGenerator) WithIDPrefix(prefix string) *IDGenerator
WithIDPrefix 设置ID前缀
func (*IDGenerator) WithIDSuffix ¶ added in v0.1.7
func (g *IDGenerator) WithIDSuffix(suffix string) *IDGenerator
WithIDSuffix 设置ID后缀
func (*IDGenerator) WithKeyPrefix ¶ added in v0.1.7
func (g *IDGenerator) WithKeyPrefix(prefix string) *IDGenerator
WithKeyPrefix 设置Redis键前缀
func (*IDGenerator) WithSeparator ¶ added in v0.1.7
func (g *IDGenerator) WithSeparator(sep string) *IDGenerator
WithSeparator 设置分隔符
func (*IDGenerator) WithSequenceInitCallback ¶ added in v0.1.7
func (g *IDGenerator) WithSequenceInitCallback(cb func() int64) *IDGenerator
WithSequenceInitCallback 设置key不存在时的序列号初始化回调
func (*IDGenerator) WithSequenceLength ¶ added in v0.1.7
func (g *IDGenerator) WithSequenceLength(length int) *IDGenerator
WithSequenceLength 设置序列号长度
func (*IDGenerator) WithSequenceStart ¶ added in v0.1.7
func (g *IDGenerator) WithSequenceStart(start int64) *IDGenerator
WithSequenceStart 设置序列号起始值
func (*IDGenerator) WithTimeFormat ¶ added in v0.1.7
func (g *IDGenerator) WithTimeFormat(format string) *IDGenerator
WithTimeFormat 设置时间格式
type LRUHandler ¶
type LRUHandler struct {
// contains filtered or unexported fields
}
LRUHandler 是一个简单的线程安全 LRU 缓存实现,满足 Handler 接口 - keys/values 使用 []byte 表示,key 在内部以 string 存储 - 当超过容量时,按最近最少使用 (LRU) 驱逐 - 支持可选的 TTL(通过 SetWithTTL)
func NewLRUHandler ¶
func NewLRUHandler(maxEntries int) *LRUHandler
NewLRUHandler 创建一个新的 LRUHandler,maxEntries<=0 表示无限容量
func (*LRUHandler) BatchGet ¶ added in v0.1.2
func (h *LRUHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取多个键的值
func (*LRUHandler) GetOrCompute ¶ added in v0.1.2
func (h *LRUHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置
func (*LRUHandler) GetTTL ¶
func (h *LRUHandler) GetTTL(key []byte) (time.Duration, error)
GetTTL 实现 Handler.GetTTL
func (*LRUHandler) Set ¶
func (h *LRUHandler) Set(key, value []byte) error
Set 实现 Handler.Set(不设置 TTL)
func (*LRUHandler) SetWithTTL ¶
func (h *LRUHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
SetWithTTL 实现 Handler.SetWithTTL
func (*LRUHandler) Stats ¶ added in v0.1.2
func (h *LRUHandler) Stats() map[string]interface{}
Stats 返回缓存统计信息
type LRUOptimizedHandler ¶ added in v0.1.2
type LRUOptimizedHandler struct {
// contains filtered or unexported fields
}
LRUOptimizedHandler 高性能分片LRU缓存处理器
func NewLRUOptimizedHandler ¶ added in v0.1.2
func NewLRUOptimizedHandler(maxEntries int) *LRUOptimizedHandler
NewLRUOptimizedHandler 创建分片式高性能LRU缓存
func (*LRUOptimizedHandler) BatchGet ¶ added in v0.1.2
func (h *LRUOptimizedHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取,减少锁开销
func (*LRUOptimizedHandler) Close ¶ added in v0.1.2
func (h *LRUOptimizedHandler) Close() error
Close 实现 Handler.Close
func (*LRUOptimizedHandler) Del ¶ added in v0.1.2
func (h *LRUOptimizedHandler) Del(key []byte) error
Del 实现 Handler.Del
func (*LRUOptimizedHandler) Get ¶ added in v0.1.2
func (h *LRUOptimizedHandler) Get(key []byte) ([]byte, error)
Get 实现 Handler.Get
func (*LRUOptimizedHandler) GetOrCompute ¶ added in v0.1.2
func (h *LRUOptimizedHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置 GetOrCompute 获取或计算值(使用singleflight防止并发重复计算)
func (*LRUOptimizedHandler) GetTTL ¶ added in v0.1.2
func (h *LRUOptimizedHandler) GetTTL(key []byte) (time.Duration, error)
GetTTL 实现 Handler.GetTTL
func (*LRUOptimizedHandler) Set ¶ added in v0.1.2
func (h *LRUOptimizedHandler) Set(key, value []byte) error
Set 实现 Handler.Set
func (*LRUOptimizedHandler) SetWithTTL ¶ added in v0.1.2
func (h *LRUOptimizedHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
SetWithTTL 实现 Handler.SetWithTTL
func (*LRUOptimizedHandler) Stats ¶ added in v0.1.2
func (h *LRUOptimizedHandler) Stats() map[string]interface{}
Stats 返回缓存统计信息
type LockConfig ¶ added in v0.1.2
type LockConfig struct {
TTL time.Duration // 锁的TTL
RetryInterval time.Duration // 重试间隔
MaxRetries int // 最大重试次数
Namespace string // 命名空间
EnableWatchdog bool // 是否启用看门狗自动续期
WatchdogInterval time.Duration // 看门狗检查间隔
}
LockConfig 锁配置
type LockManager ¶ added in v0.1.2
type LockManager struct {
// contains filtered or unexported fields
}
LockManager 锁管理器
func NewLockManager ¶ added in v0.1.2
func NewLockManager(redisClient redis.UniversalClient, config ...LockConfig) *LockManager
NewLockManager 创建锁管理器
func (*LockManager) CleanupExpiredLocks ¶ added in v0.1.2
func (m *LockManager) CleanupExpiredLocks(ctx context.Context) error
CleanupExpiredLocks 清理过期的锁
func (*LockManager) GetAllLockStats ¶ added in v0.1.2
GetAllLockStats 获取管理器中所有锁的统计信息
func (*LockManager) GetLock ¶ added in v0.1.2
func (m *LockManager) GetLock(key string) *DistributedLock
GetLock 获取或创建锁
func (*LockManager) ReleaseAllLocks ¶ added in v0.1.2
func (m *LockManager) ReleaseAllLocks(ctx context.Context) error
ReleaseAllLocks 释放所有锁
func (*LockManager) ReleaseLock ¶ added in v0.1.2
func (m *LockManager) ReleaseLock(ctx context.Context, key string) error
ReleaseLock 释放锁并从管理器中移除
type LockStats ¶ added in v0.1.2
type LockStats struct {
Key string `json:"key"`
Token string `json:"token"`
Acquired bool `json:"acquired"`
ExpireTime time.Time `json:"expire_time"`
TTL time.Duration `json:"ttl"`
WatchdogActive bool `json:"watchdog_active"`
}
GetLockStats 获取锁统计信息
type MessageHandler ¶ added in v0.1.2
MessageHandler 消息处理器接口
type MultiLevelCache ¶ added in v0.1.7
type MultiLevelCache[T any] struct { // contains filtered or unexported fields }
MultiLevelCache 多级缓存(生产级别)
func NewMultiLevelCache ¶ added in v0.1.7
func NewMultiLevelCache[T any](redisClient redis.UniversalClient, config MultiLevelConfig) *MultiLevelCache[T]
NewMultiLevelCache 创建多级缓存
func (*MultiLevelCache[T]) Clear ¶ added in v0.1.7
func (m *MultiLevelCache[T]) Clear(ctx context.Context) error
Clear 清空所有缓存
func (*MultiLevelCache[T]) Delete ¶ added in v0.1.7
func (m *MultiLevelCache[T]) Delete(ctx context.Context, key string) error
Delete 删除缓存
func (*MultiLevelCache[T]) Get ¶ added in v0.1.7
func (m *MultiLevelCache[T]) Get(ctx context.Context, key string, loader func() (T, error)) (T, error)
Get 获取缓存(L1 → L2 → 加载器)
func (*MultiLevelCache[T]) GetStats ¶ added in v0.1.7
func (m *MultiLevelCache[T]) GetStats() map[string]int64
func (*MultiLevelCache[T]) InvalidateL1 ¶ added in v0.1.7
func (m *MultiLevelCache[T]) InvalidateL1(key string)
InvalidateL1 使L1缓存失效
type MultiLevelConfig ¶ added in v0.1.7
type MultiLevelConfig struct {
Namespace string
L1Size int // L1本地缓存大小
L1TTL time.Duration // L1缓存过期时间
L2TTL time.Duration // L2 Redis缓存过期时间
EnableCompression bool // 是否启用压缩
SyncInterval time.Duration // 同步间隔
}
MultiLevelConfig 多级缓存配置
type PubSub ¶ added in v0.1.2
type PubSub struct {
// contains filtered or unexported fields
}
PubSub Redis发布订阅封装
func NewPubSub ¶ added in v0.1.2
func NewPubSub(redisClient redis.UniversalClient, config ...PubSubConfig) *PubSub
NewPubSub 创建发布订阅实例
func (*PubSub) BroadcastMessage ¶ added in v0.1.2
func (p *PubSub) BroadcastMessage(ctx context.Context, channels []string, message interface{}) error
BroadcastMessage 广播消息到多个频道
func (*PubSub) GetChannels ¶ added in v0.1.2
GetChannels 获取已订阅的频道列表
func (*PubSub) GetSubscribers ¶ added in v0.1.2
GetSubscribers 获取活跃的订阅者数量
func (*PubSub) RequestResponse ¶ added in v0.1.2
func (p *PubSub) RequestResponse(ctx context.Context, requestChannel, responseChannel string, request interface{}, timeout time.Duration) (string, error)
RequestResponse 请求-响应模式(基于发布订阅)
func (*PubSub) Subscribe ¶ added in v0.1.2
func (p *PubSub) Subscribe(channels []string, handler MessageHandler) (*Subscriber, error)
Subscribe 订阅频道
func (*PubSub) SubscribePattern ¶ added in v0.1.2
func (p *PubSub) SubscribePattern(patterns []string, handler MessageHandler) (*Subscriber, error)
SubscribePattern 订阅模式匹配的频道
func (*PubSub) Unsubscribe ¶ added in v0.1.2
Unsubscribe 取消订阅
type PubSubConfig ¶ added in v0.1.2
type PubSubConfig struct {
Namespace string // 命名空间
MaxRetries int // 最大重试次数
RetryDelay time.Duration // 重试延迟
BufferSize int // 消息缓冲区大小
EnableLogging bool // 是否启用日志
PingInterval time.Duration // 心跳间隔
}
PubSubConfig 发布订阅配置
func DefaultPubSubConfig ¶ added in v0.1.2
func DefaultPubSubConfig() PubSubConfig
DefaultPubSubConfig 默认配置
type PubSubStats ¶ added in v0.1.2
type PubSubStats struct {
ActiveSubscribers int `json:"active_subscribers"`
Channels []string `json:"channels"`
Patterns []string `json:"patterns"`
}
PubSubStats 发布订阅统计
type QueueConfig ¶ added in v0.1.2
type QueueConfig struct {
MaxRetries int // 最大重试次数
RetryDelay time.Duration // 重试延迟
BatchSize int // 批处理大小
LockTimeout time.Duration // 分布式锁超时时间
CleanupInterval time.Duration // 清理间隔
EnableDistributedLock bool // 是否启用分布式锁
}
QueueConfig 队列配置
type QueueHandler ¶ added in v0.1.2
type QueueHandler struct {
// contains filtered or unexported fields
}
QueueHandler Redis队列处理器
func NewQueueHandler ¶ added in v0.1.2
func NewQueueHandler(client *redis.Client, namespace string, config QueueConfig) *QueueHandler
NewQueueHandler 创建队列处理器
func (*QueueHandler) AcquireLock ¶ added in v0.1.2
func (q *QueueHandler) AcquireLock(ctx context.Context, queueName string, workerID string) (bool, error)
AcquireLock 获取分布式锁
func (*QueueHandler) BatchDequeue ¶ added in v0.1.2
func (q *QueueHandler) BatchDequeue(ctx context.Context, queueName string, queueType QueueType, count int) ([]*QueueItem, error)
BatchDequeue 批量出队
func (*QueueHandler) Contains ¶ added in v0.1.2
func (q *QueueHandler) Contains(ctx context.Context, queueName string, queueType QueueType, itemID string) (bool, error)
Contains 检查队列是否包含特定元素
func (*QueueHandler) Dequeue ¶ added in v0.1.2
func (q *QueueHandler) Dequeue(ctx context.Context, queueName string, queueType QueueType) (*QueueItem, error)
Dequeue 出队操作
func (*QueueHandler) DequeueNonBlocking ¶ added in v0.1.2
func (q *QueueHandler) DequeueNonBlocking(ctx context.Context, queueName string, queueType QueueType) (*QueueItem, error)
DequeueNonBlocking 非阻塞出队操作
func (*QueueHandler) Enqueue ¶ added in v0.1.2
func (q *QueueHandler) Enqueue(ctx context.Context, queueName string, queueType QueueType, item *QueueItem) error
Enqueue 入队操作
func (*QueueHandler) GetFailedItems ¶ added in v0.1.2
func (q *QueueHandler) GetFailedItems(ctx context.Context, queueName string, offset, limit int64) ([]*QueueItem, error)
GetFailedItems 获取失败的任务
func (*QueueHandler) GetStats ¶ added in v0.1.2
func (q *QueueHandler) GetStats(ctx context.Context, queueName string, queueType QueueType) (*QueueStats, error)
GetStats 获取队列统计信息
func (*QueueHandler) Length ¶ added in v0.1.2
func (q *QueueHandler) Length(ctx context.Context, queueName string, queueType QueueType) (int64, error)
Length 获取队列长度
func (*QueueHandler) Peek ¶ added in v0.1.2
func (q *QueueHandler) Peek(ctx context.Context, queueName string, queueType QueueType, count int) ([]*QueueItem, error)
Peek 查看队列头部元素(不移除)
func (*QueueHandler) ReleaseLock ¶ added in v0.1.2
ReleaseLock 释放分布式锁
func (*QueueHandler) RetryFailed ¶ added in v0.1.2
func (q *QueueHandler) RetryFailed(ctx context.Context, queueName string, queueType QueueType, item *QueueItem) error
RetryFailed 重试失败的任务
type QueueItem ¶ added in v0.1.2
type QueueItem struct {
ID string `json:"id"` // 唯一标识
Data interface{} `json:"data"` // 数据内容
Priority float64 `json:"priority"` // 优先级(用于优先级队列)
DelayTime int64 `json:"delay_time"` // 延时时间戳(用于延时队列)
CreatedAt int64 `json:"created_at"` // 创建时间
RetryCount int `json:"retry_count"` // 重试次数
}
QueueItem 队列项
type QueueStats ¶ added in v0.1.2
type QueueStats struct {
QueueName string `json:"queue_name"`
QueueType string `json:"queue_type"`
Length int64 `json:"length"`
DelayedCount int64 `json:"delayed_count,omitempty"`
FailedCount int64 `json:"failed_count"`
}
Statistics 获取队列统计信息
type RedisHandler ¶
type RedisHandler struct {
// contains filtered or unexported fields
}
RedisHandler 是 Redis 缓存的实现
func (*RedisHandler) BatchGet ¶ added in v0.1.2
func (h *RedisHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取多个键的值
func (*RedisHandler) Get ¶
func (h *RedisHandler) Get(k []byte) ([]byte, error)
Get 实现 Handler 接口的 Get 方法
func (*RedisHandler) GetOrCompute ¶ added in v0.1.2
func (h *RedisHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置
func (*RedisHandler) GetTTL ¶
func (h *RedisHandler) GetTTL(k []byte) (time.Duration, error)
GetTTL 实现 Handler 接口的 GetTTL 方法
func (*RedisHandler) SetWithTTL ¶
func (h *RedisHandler) SetWithTTL(k, v []byte, ttl time.Duration) error
SetWithTTL 实现 Handler 接口的 SetWithTTL 方法
func (*RedisHandler) Stats ¶ added in v0.1.2
func (h *RedisHandler) Stats() map[string]interface{}
Stats 返回Redis缓存统计信息
func (*RedisHandler) WithCtx ¶
func (h *RedisHandler) WithCtx(ctx context.Context) *RedisHandler
type RistrettoConfig ¶
type RistrettoConfig struct {
NumCounters int64 // 计数器数量,用于跟踪访问频率
MaxCost int64 // 最大缓存成本
BufferItems int64 // Get 缓存的大小
Metrics bool // 是否启用缓存统计
OnEvict func(item *ristretto.Item[[]byte]) // 每次驱逐时调用
OnReject func(item *ristretto.Item[[]byte]) // 每次拒绝时调用
OnExit func(val []byte) // 从缓存中移除值时调用
ShouldUpdate func(cur, prev []byte) bool // 更新时的检查函数
KeyToHash func(key []byte) (uint64, uint64) // 自定义键哈希算法
Cost func(value []byte) int64 // 计算值的成本
IgnoreInternalCost bool // 是否忽略内部存储的成本
TtlTickerDurationInSec int64 // TTL 过期时清理键的时间间隔 (为0时=bucketDurationSecs)
}
Config 用于定制 Ristretto 缓存的配置
func NewDefaultRistrettoConfig ¶
func NewDefaultRistrettoConfig() *RistrettoConfig
NewDefaultRistrettoConfig 创建一个新的ristretto配置实例
func (*RistrettoConfig) EnableMetrics ¶
func (c *RistrettoConfig) EnableMetrics() *RistrettoConfig
EnableMetrics 启用缓存统计
func (*RistrettoConfig) SetBufferItems ¶
func (c *RistrettoConfig) SetBufferItems(bufferItems int64) *RistrettoConfig
SetBufferItems 设置 Get 缓存的大小
func (*RistrettoConfig) SetCost ¶
func (c *RistrettoConfig) SetCost(fn func(value []byte) int64) *RistrettoConfig
SetCost 设置计算值成本的函数
func (*RistrettoConfig) SetIgnoreInternalCost ¶
func (c *RistrettoConfig) SetIgnoreInternalCost(ignore bool) *RistrettoConfig
SetIgnoreInternalCost 设置是否忽略内部存储的成本
func (*RistrettoConfig) SetKeyToHash ¶
func (c *RistrettoConfig) SetKeyToHash(fn func(key []byte) (uint64, uint64)) *RistrettoConfig
SetKeyToHash 设置自定义键哈希算法
func (*RistrettoConfig) SetMaxCost ¶
func (c *RistrettoConfig) SetMaxCost(maxCost int64) *RistrettoConfig
SetMaxCost 设置最大缓存成本
func (*RistrettoConfig) SetNumCounters ¶
func (c *RistrettoConfig) SetNumCounters(numCounters int64) *RistrettoConfig
SetNumCounters 设置计数器数量
func (*RistrettoConfig) SetOnEvict ¶
func (c *RistrettoConfig) SetOnEvict(fn func(item *ristretto.Item[[]byte])) *RistrettoConfig
SetOnEvict 设置驱逐时的回调函数
func (*RistrettoConfig) SetOnExit ¶
func (c *RistrettoConfig) SetOnExit(fn func(val []byte)) *RistrettoConfig
SetOnExit 设置从缓存中移除值时的回调函数
func (*RistrettoConfig) SetOnReject ¶
func (c *RistrettoConfig) SetOnReject(fn func(item *ristretto.Item[[]byte])) *RistrettoConfig
SetOnReject 设置拒绝时的回调函数
func (*RistrettoConfig) SetShouldUpdate ¶
func (c *RistrettoConfig) SetShouldUpdate(fn func(cur, prev []byte) bool) *RistrettoConfig
SetShouldUpdate 设置更新时的检查函数
func (*RistrettoConfig) SetTtlTickerDurationInSec ¶
func (c *RistrettoConfig) SetTtlTickerDurationInSec(duration int64) *RistrettoConfig
SetTtlTickerDurationInSec 设置 TTL 过期时间间隔
type RistrettoHandler ¶
type RistrettoHandler struct {
// contains filtered or unexported fields
}
RistrettoHandler 是 Ristretto 缓存的实现
func NewDefaultRistrettoHandler ¶
func NewDefaultRistrettoHandler() (*RistrettoHandler, error)
NewDefaultRistrettoHandler 创建默认的 RistrettoHandler
func NewRistrettoHandler ¶
func NewRistrettoHandler(config *RistrettoConfig) (*RistrettoHandler, error)
NewRistrettoHandler 创建新的 RistrettoHandler,支持自定义配置
func (*RistrettoHandler) BatchGet ¶ added in v0.1.2
func (h *RistrettoHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取多个键的值
func (*RistrettoHandler) Close ¶
func (h *RistrettoHandler) Close() error
Close 实现 Handler 接口的 Close 方法
func (*RistrettoHandler) Del ¶
func (h *RistrettoHandler) Del(k []byte) error
Del 实现 Handler 接口的 Del 方法
func (*RistrettoHandler) Get ¶
func (h *RistrettoHandler) Get(k []byte) ([]byte, error)
Get 实现 Handler 接口的 Get 方法
func (*RistrettoHandler) GetOrCompute ¶ added in v0.1.2
func (h *RistrettoHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置
func (*RistrettoHandler) GetTTL ¶
func (h *RistrettoHandler) GetTTL(k []byte) (time.Duration, error)
GetTTL 实现 Handler 接口的 GetTTL 方法
func (*RistrettoHandler) Set ¶
func (h *RistrettoHandler) Set(k, v []byte) error
Set 实现 Handler 接口的 Set 方法
func (*RistrettoHandler) SetWithTTL ¶
func (h *RistrettoHandler) SetWithTTL(k, v []byte, ttl time.Duration) error
SetWithTTL 实现 Handler 接口的 SetWithTTL 方法
func (*RistrettoHandler) Stats ¶ added in v0.1.2
func (h *RistrettoHandler) Stats() map[string]interface{}
Stats 返回缓存统计信息
type SQLDataLoader ¶ added in v0.1.2
type SQLDataLoader[K comparable, V any] struct { QueryFunc func(ctx context.Context) (map[K]V, error) }
SQLDataLoader SQL数据加载器
type ShardedHandler ¶
type ShardedHandler struct {
// contains filtered or unexported fields
}
ShardedHandler 将缓存分成多个 shard,每个 shard 使用独立的 Handler 实例 适用于降低单锁争用或使用多实例后端的场景
func NewShardedHandler ¶
func NewShardedHandler(factory func() Handler, shards int) *ShardedHandler
NewShardedHandler 使用 factory 创建 shards 个 Handler
func (*ShardedHandler) BatchGet ¶ added in v0.1.2
func (h *ShardedHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取多个键的值
func (*ShardedHandler) GetOrCompute ¶ added in v0.1.2
func (h *ShardedHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置
func (*ShardedHandler) GetTTL ¶
func (h *ShardedHandler) GetTTL(key []byte) (time.Duration, error)
GetTTL 转发
func (*ShardedHandler) Set ¶
func (h *ShardedHandler) Set(key, value []byte) error
Set 将请求转发到对应的 shard
func (*ShardedHandler) SetWithTTL ¶
func (h *ShardedHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
SetWithTTL 转发
func (*ShardedHandler) Stats ¶ added in v0.1.2
func (h *ShardedHandler) Stats() map[string]interface{}
Stats 返回所有分片的统计信息
type SmartCache ¶ added in v0.1.7
type SmartCache struct {
// contains filtered or unexported fields
}
SmartCache 智能缓存 - 集成多种高级功能
func (*SmartCache) Delete ¶ added in v0.1.7
func (c *SmartCache) Delete(ctx context.Context, key string) error
Delete 删除缓存
func (*SmartCache) Get ¶ added in v0.1.7
func (c *SmartCache) Get(ctx context.Context, key string) (interface{}, error)
Get 获取缓存(支持自动加载和刷新)
func (*SmartCache) GetOrSet ¶ added in v0.1.7
func (c *SmartCache) GetOrSet(ctx context.Context, key string, loader func() (interface{}, error)) (interface{}, error)
GetOrSet 获取或设置缓存(简化版) - 使用singleflight优化
func (*SmartCache) Set ¶ added in v0.1.7
func (c *SmartCache) Set(ctx context.Context, key string, value interface{}, ttl ...time.Duration) error
Set 设置缓存
func (*SmartCache) Subscribe ¶ added in v0.1.7
func (c *SmartCache) Subscribe(ctx context.Context, event string, handler func(data interface{})) (*Subscriber, error)
Subscribe 订阅缓存事件
type Subscriber ¶ added in v0.1.2
type Subscriber struct {
// contains filtered or unexported fields
}
Subscriber 订阅者
func SimpleSubscribe ¶ added in v0.1.2
func SimpleSubscribe(client *redis.Client, channel string, handler MessageHandler) (*Subscriber, error)
SimpleSubscribe 简单订阅消息
func SubscribeJSON ¶ added in v0.1.2
func SubscribeJSON[T any](p *PubSub, channels []string, handler TypedMessageHandler[T]) (*Subscriber, error)
SubscribeJSON 订阅JSON消息(泛型版本)
func (*Subscriber) GetChannels ¶ added in v0.1.2
func (s *Subscriber) GetChannels() []string
GetChannels 获取订阅的频道
func (*Subscriber) IsActive ¶ added in v0.1.2
func (s *Subscriber) IsActive() bool
IsActive 检查订阅是否活跃
type TwoLevelHandler ¶
type TwoLevelHandler struct {
L1 Handler
L2 Handler
WriteThrough bool // 如果 true,Set 同步写入 L1 和 L2;否则异步写入 L2
}
TwoLevelHandler 提供 L1/L2 两级缓存封装,兼容 Handler 接口 L1 通常是快速但容量有限的本地缓存(例如 LRU),L2 是容量更大或远程的缓存(例如 Ristretto/Redis)
func NewTwoLevelHandler ¶
func NewTwoLevelHandler(l1, l2 Handler, writeThrough bool) *TwoLevelHandler
func (*TwoLevelHandler) BatchGet ¶ added in v0.1.2
func (h *TwoLevelHandler) BatchGet(keys [][]byte) ([][]byte, []error)
BatchGet 批量获取多个键的值
func (*TwoLevelHandler) Close ¶
func (h *TwoLevelHandler) Close() error
func (*TwoLevelHandler) Del ¶
func (h *TwoLevelHandler) Del(key []byte) error
func (*TwoLevelHandler) GetOrCompute ¶ added in v0.1.2
func (h *TwoLevelHandler) GetOrCompute(key []byte, ttl time.Duration, loader func() ([]byte, error)) ([]byte, error)
GetOrCompute 获取缓存值,如果不存在则计算并设置
func (*TwoLevelHandler) GetTTL ¶
func (h *TwoLevelHandler) GetTTL(key []byte) (time.Duration, error)
func (*TwoLevelHandler) Set ¶
func (h *TwoLevelHandler) Set(key, value []byte) error
func (*TwoLevelHandler) SetWithTTL ¶
func (h *TwoLevelHandler) SetWithTTL(key, value []byte, ttl time.Duration) error
func (*TwoLevelHandler) Stats ¶ added in v0.1.2
func (h *TwoLevelHandler) Stats() map[string]interface{}
Stats 返回两级缓存的统计信息
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 20:53:00 * @FilePath: \go-cachex\examples\advanced_usage.go * @Description: go-cachex 高级功能使用示例 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
|
* @Author: kamalyes [email protected] * @Date: 2025-11-19 00:00:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-19 20:53:00 * @FilePath: \go-cachex\examples\advanced_usage.go * @Description: go-cachex 高级功能使用示例 * * Copyright (c) 2025 by kamalyes, All Rights Reserved. |
|
ctxcache
command
* @Author: kamalyes [email protected] * @Date: 2025-11-09 21:12:18 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 21:45:21 * @FilePath: \go-cachex\examples\ctxcache\advanced.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
|
* @Author: kamalyes [email protected] * @Date: 2025-11-09 21:12:18 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 21:45:21 * @FilePath: \go-cachex\examples\ctxcache\advanced.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved. |
|
expiring
command
* @Description: Expiring Cache 高级使用示例
|
* @Description: Expiring Cache 高级使用示例 |
|
interface_test
command
|
|
|
lru
command
|
|
|
lru_optimized
command
* @Author: kamalyes [email protected] * @Date: 2025-11-09 22:45:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 22:45:00 * @FilePath: \go-cachex\examples\lru_optimized\basic.go * @Description: LRU优化版本客户端基础使用示例 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
|
* @Author: kamalyes [email protected] * @Date: 2025-11-09 22:45:00 * @LastEditors: kamalyes [email protected] * @LastEditTime: 2025-11-09 22:45:00 * @FilePath: \go-cachex\examples\lru_optimized\basic.go * @Description: LRU优化版本客户端基础使用示例 * * Copyright (c) 2025 by kamalyes, All Rights Reserved. |
|
ristretto
command
|
|
|
sharded
command
* @Description: Sharded Cache 高级使用示例
|
* @Description: Sharded Cache 高级使用示例 |
|
twolevel
command
* @Description: TwoLevel Cache 高级使用示例
|
* @Description: TwoLevel Cache 高级使用示例 |