cachex

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

README

Go-Cachex

Go-Cachex 是一个全面的缓存库,提供多种缓存实现和适配器,支持 TTL、LRU 驱逐、并发安全、分布式锁、队列、发布订阅和上下文感知等特性。

stable license download release commit issues pull fork star go size contributors codecov Go Report Card Go Reference Sourcegraph

📚 目录

🏗️ 架构设计

Go-Cachex 采用模块化分层架构设计,提供灵活且强大的缓存解决方案:

┌─────────────────────────────────────────────────────────────┐
│                        用户代码                              │
└─────────────────────────┬───────────────────────────────────┘
                         │
┌─────────────────────────▼───────────────────────────────────┐
│              Client (统一入口 + 配置管理)                    │
└─────────────────────────┬───────────────────────────────────┘
                         │
┌─────────────────────────▼───────────────────────────────────┐
│        CtxCache (context 支持 + singleflight 去重)          │
└─────────────────────────┬───────────────────────────────────┘
                         │
┌─────────────────────────▼───────────────────────────────────┐
│  Handler (缓存实现:LRU/Redis/Ristretto/Expiring/等)        │
└─────────────────────┬───┬───┬───┬─────────────────────────────┘
                     │   │   │   │
              ┌──────▼─┐ ┌▼─┐ ┌▼─┐ ┌▼──────────────┐
              │ Memory │ │队列│ │锁│ │ 发布订阅      │
              └────────┘ └──┘ └──┘ └───────────────┘
🎯 架构层次
  • Client 层:统一的用户接口,提供配置管理和便利函数
  • CtxCache 层:为底层 Handler 添加 context 支持和并发去重功能
  • Handler 层:具体的缓存实现,支持多种存储后端
  • 扩展层:队列、锁、发布订阅等高级功能

✨ 功能特性

🚀 核心缓存功能
多种缓存后端
  • LRU Cache: 内存 LRU 缓存,支持容量限制和 TTL
  • LRU Optimized: 超高性能分片架构LRU (500%+性能提升)
  • Ristretto Cache: 基于频率的并发缓存,最佳缓存命中率
  • Redis Cache: 分布式缓存后端,支持故障转移
  • TwoLevel Cache: 智能分层缓存,L1快速缓存 + L2存储缓存
  • Sharded Cache: 分布式负载,减少锁竞争
  • Expiring Cache: 简单的 TTL 缓存,后台自动清理
统一Handler接口
type Handler interface {
    Set(key, value []byte) error
    SetWithTTL(key, value []byte, ttl time.Duration) error
    Get(key []byte) ([]byte, error)
    GetTTL(key []byte) ([]byte, time.Duration, error)
    Del(key []byte) error
    BatchGet(keys [][]byte) ([][]byte, []error)
    Stats() Stats
    Close() error
}
🔥 高级特性
队列系统
  • 多种队列类型: FIFO、LIFO、优先级、延迟队列
  • 批量操作: 支持批量入队/出队提升性能
  • 分布式锁: 可选的队列操作锁定机制
  • 重试机制: 失败任务自动重试
  • 统计监控: 队列状态和性能统计
分布式锁
  • Redis分布式锁: 基于Redis的高可用分布式锁
  • 可选看门狗: 自动续期防止锁过期
  • 锁竞争统计: 详细的锁使用统计
  • 超时控制: 灵活的锁获取超时配置
发布订阅系统
  • Redis Pub/Sub: 高性能消息发布订阅
  • 模式订阅: 支持通配符模式订阅
  • 请求响应: 内置请求响应通信模式
  • 消息重试: 可配置的消息处理重试
  • 统计监控: 消息传递统计和监控
热Key缓存
  • SQL数据加载: 支持从数据库加载热点数据
  • Redis存储: 使用Redis作为分布式存储
  • 自动刷新: 可配置的定时数据刷新
  • 缓存预热: 启动时预加载热点数据
缓存包装器 🆕
  • 泛型支持: 支持任意类型的数据缓存 CacheWrapper[T]
  • 延迟双删: 实现延迟双删策略,确保缓存一致性
  • 数据压缩: 自动Zlib压缩,减少Redis内存占用
  • 错误处理: 优雅的错误处理和降级机制
  • 并发安全: 支持高并发访问,适用于生产环境
性能与监控
Context 支持
  • 上下文取消: 所有操作支持 context,可实现超时控制
  • 并发去重: 内置 singleflight 机制,避免重复计算
  • GetOrCompute: 智能加载函数,缓存未命中时自动计算
统计与监控
  • 性能指标: 命中率、操作计数、延迟统计
  • 容量信息: 当前条目、最大容量、内存使用
  • 架构细节: 分片计数、驱逐统计、后端状态
  • 健康状态: 连接状态、错误率、过期计数
高性能优化
  • 零拷贝技术: 减少内存分配和复制
  • 分片架构: 减少锁竞争,提升并发性能
  • 批量操作: 优化网络和CPU使用率
  • 内存池: 对象重用减少GC压力

🚀 快速开始

环境要求

建议需要 Go 版本 1.23 或更高版本

安装
go get -u github.com/kamalyes/go-cachex
快速示例
package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/kamalyes/go-cachex"
)

func main() {
    ctx := context.Background()
    
    // 创建 LRU 缓存客户端
    client, err := cachex.NewLRUClient(ctx, 1000)
    if err != nil {
        panic(err)
    }
    defer client.Close()
    
    // 基本操作
    err = client.Set(ctx, []byte("hello"), []byte("world"))
    if err != nil {
        panic(err)
    }
    
    val, err := client.Get(ctx, []byte("hello"))
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Value: %s\n", string(val))
    
    // 使用 GetOrCompute
    result, err := client.GetOrCompute(ctx, []byte("computed"), 
        func(ctx context.Context) ([]byte, error) {
            return []byte("computed value"), nil
        })
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Computed: %s\n", string(result))
}
CacheWrapper 示例
package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/redis/go-redis/v9"
    "github.com/kamalyes/go-cachex"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    // 创建Redis客户端
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })
    defer client.Close()

    // 创建用户数据加载器
    userLoader := cachex.CacheWrapper(client, "user:123",
        func(ctx context.Context) (*User, error) {
            // 模拟数据库查询
            fmt.Println("Loading user from database...")
            return &User{ID: 123, Name: "Alice"}, nil
        },
        time.Hour, // 缓存1小时
    )

    ctx := context.Background()
    
    // 第一次调用 - 从数据库加载
    user, err := userLoader(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Printf("User: %+v\n", user)
    
    // 第二次调用 - 从缓存获取
    user2, err := userLoader(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Cached User: %+v\n", user2)
}

🧩 核心组件

缓存客户端
  • NewLRUClient() - 内存LRU缓存
  • NewLRUOptimizedClient() - 高性能分片LRU
  • NewRedisClient() - Redis分布式缓存
  • NewRistrettoClient() - 高性能Ristretto缓存
  • NewTwoLevelClient() - 两级缓存系统
缓存包装器
  • CacheWrapper[T]() - 泛型缓存包装器,支持任意类型
  • 延迟双删策略,确保缓存一致性
  • 自动数据压缩,节省存储空间
  • 优雅的错误处理和降级机制
队列系统
  • NewQueueHandler() - 创建队列处理器
  • QueueType - FIFO/LIFO/Priority/Delayed
  • ProcessWithLock() - 支持分布式锁的处理
分布式锁
  • NewDistributedLock() - 创建分布式锁
  • TryLock() / Lock() - 获取锁
  • Unlock() - 释放锁
发布订阅
  • NewPubSub() - 创建发布订阅客户端
  • Subscribe() - 订阅消息
  • Publish() - 发布消息
热Key缓存
  • NewHotKeyCache() - 创建热key缓存
  • DataLoader - 数据加载器接口
  • Refresh() - 手动刷新数据

📖 文档索引

📋 基础文档
🔧 组件文档
📊 性能与架构
💻 开发指南

🏃‍♂️ 示例代码

各组件的详细示例请查看 examples/ 目录:

📈 性能报告

基准测试结果
组件 操作/秒 延迟 内存使用 提升
LRU Optimized 2.8M ops/s 0.35μs 354 bytes/entry +500%
Standard LRU 500K ops/s 2.0μs 18TB bytes/entry baseline
Ristretto 1.2M ops/s 0.83μs Variable +140%
Redis Cache 100K ops/s 10μs Network N/A

详细性能分析请查看 PERFORMANCE-REPORT.md

优化特性
  • 零拷贝技术: 减少70%的内存分配
  • 分片架构: 16分片设计,减少99%的锁竞争
  • 批量操作: 网络操作性能提升10倍
  • 对象池: GC压力减少80%

🤝 贡献指南

我们欢迎各种形式的贡献!

如何贡献
  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request
开发要求
  • Go 1.23+
  • 单元测试覆盖率 > 90%
  • 遵循 Go 代码规范
  • 添加适当的文档和示例
问题报告

如果发现 bug 或有功能建议,请通过 Issues 提交。

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

🙏 致谢

感谢所有为本项目做出贡献的开发者!


如果觉得这个项目对您有帮助,请给我们一个 ⭐ Star!

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

Constants

This section is empty.

Variables

View Source
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")

	// ErrUnavailable 表示缓存服务暂时不可用(比如 Redis 连接断开)
	// 当底层存储服务(如Redis、Memcached等)连接失败或不可达时返回此错误
	ErrUnavailable = errors.New("cache service unavailable")

	// ErrTimeout 表示操作超时
	// 当缓存操作执行时间超过设定的超时时间时返回此错误
	ErrTimeout = errors.New("cache operation timed out")
)
View Source
var (
	ErrLockNotFound    = errors.New("lock not found")
	ErrLockNotObtained = errors.New("lock not obtained")
	ErrLockExpired     = errors.New("lock has expired")
	ErrLockNotOwned    = errors.New("lock not owned by this instance")
)

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

func NewRedisOptions(addr, password string, db int) *redis.Options

NewRedisOptions 创建推荐的Redis配置 这个函数设置了一些推荐的默认值以避免常见的警告和问题

func PublishJSON added in v0.1.2

func PublishJSON[T any](p *PubSub, ctx context.Context, channel string, message T) error

PublishJSON 发布JSON消息(泛型版本)

func SimplePublish added in v0.1.2

func SimplePublish(client *redis.Client, channel string, message interface{}) error

SimplePublish 简单发布消息

func ValidateBasicOp

func ValidateBasicOp(key []byte, initialized, closed bool) error

ValidateBasicOp 验证基本操作的参数(检查键、缓存状态)

func ValidateCapacity

func ValidateCapacity(current, max int) error

ValidateCapacity 验证是否超出容量限制

func ValidateClosed

func ValidateClosed(closed bool) error

ValidateClosed 验证缓存是否已关闭

func ValidateInitialized

func ValidateInitialized(initialized bool) error

ValidateInitialized 验证缓存是否已初始化

func ValidateKey

func ValidateKey(key []byte) error

ValidateKey 验证键是否有效

func ValidateTTL

func ValidateTTL(ttl time.Duration) error

ValidateTTL 验证 TTL 是否有效(允许 -1 表示无限期)

func ValidateValue

func ValidateValue(value []byte) error

ValidateValue 验证值是否有效

func ValidateWriteOp

func ValidateWriteOp(key, value []byte, initialized, closed bool) error

ValidateWriteOp 验证写操作的参数(检查键、值、缓存状态)

func ValidateWriteWithTTLOp

func ValidateWriteWithTTLOp(key, value []byte, ttl time.Duration, initialized, closed bool) error

ValidateWriteWithTTLOp 验证带 TTL 的写操作参数

func WithCache

func WithCache(ctx context.Context, c *CtxCache) context.Context

WithCache 把 CtxCache 写入 ctx

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]) BatchGet added in v0.1.2

func (c *AdvancedCache[T]) BatchGet(ctx context.Context, keys []string) (map[string]T, error)

BatchGet 批量获取

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]) Exists added in v0.1.2

func (c *AdvancedCache[T]) Exists(ctx context.Context, keys ...string) (int64, error)

Exists 检查键是否存在

func (*AdvancedCache[T]) Expire added in v0.1.2

func (c *AdvancedCache[T]) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire 设置键的过期时间

func (*AdvancedCache[T]) Get added in v0.1.2

func (c *AdvancedCache[T]) Get(ctx context.Context, key string) (T, bool, error)

Get 获取缓存

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]) Keys added in v0.1.2

func (c *AdvancedCache[T]) Keys(ctx context.Context, pattern string) ([]string, error)

Keys 获取匹配模式的所有键

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]) TTL added in v0.1.2

func (c *AdvancedCache[T]) TTL(ctx context.Context, key string) (time.Duration, error)

TTL 获取键的TTL

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

type CacheFunc[T any] func(ctx context.Context) (T, error)

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缓存功能。

该函数实现了以下核心特性:

  1. 缓存查询:首先尝试从Redis获取缓存数据
  2. 数据压缩:使用Zlib算法压缩缓存数据,减少内存使用
  3. 延迟双删:实现延迟双删策略,防止并发写入导致的缓存不一致
  4. 错误处理:区分Redis连接错误和键不存在错误,优雅降级

缓存流程:

  1. 尝试从Redis获取缓存数据
  2. 如果缓存存在且有效,解压缩并反序列化返回
  3. 如果缓存不存在或无效,执行原始数据加载函数
  4. 将加载的数据序列化、压缩后存储到Redis
  5. 执行延迟双删策略确保缓存一致性

延迟双删策略:

  • 第一次删除:在设置新缓存前删除旧缓存
  • 设置缓存:存储新的缓存数据
  • 延迟删除: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 CacheType added in v0.1.1

type CacheType string

CacheType 定义支持的缓存类型

const (
	CacheLRU          CacheType = "lru"
	CacheLRUOptimized CacheType = "lru_optimized"
	CacheRistretto    CacheType = "ristretto"
	CacheRedis        CacheType = "redis"
	CacheExpiring     CacheType = "expiring"
)

type CacheWrapperFunc added in v0.1.2

type CacheWrapperFunc[T any] func(ctx context.Context) (T, error)

CacheWrapper 缓存包装器函数类型

type Case added in v0.1.5

type Case struct {
	Condition bool        // 条件
	Opt       CacheOption // 选项
}

Case 条件-选项对

func NewCase added in v0.1.5

func NewCase(condition bool, opt CacheOption) Case

NewCase 创建条件-选项对

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

func NewExpiringClient(ctx context.Context, cleanupInterval time.Duration) (*Client, error)

NewExpiringClient 创建过期缓存客户端的便利函数

func NewLRUClient added in v0.1.2

func NewLRUClient(ctx context.Context, capacity int) (*Client, error)

NewLRUClient 创建 LRU 缓存客户端的便利函数

func NewLRUOptimizedClient added in v0.1.2

func NewLRUOptimizedClient(ctx context.Context, capacity int) (*Client, error)

NewLRUOptimizedClient 创建优化版本 LRU 缓存客户端的便利函数

func NewRedisClient added in v0.1.2

func NewRedisClient(ctx context.Context, opts *redis.Options) (*Client, error)

NewRedisClient 创建 Redis 缓存客户端的便利函数

func NewRistrettoClient added in v0.1.2

func NewRistrettoClient(ctx context.Context, config *RistrettoConfig) (*Client, error)

NewRistrettoClient 创建 Ristretto 缓存客户端的便利函数

func (*Client) BatchGet added in v0.1.2

func (c *Client) BatchGet(ctx context.Context, keys [][]byte) ([][]byte, []error)

BatchGet 批量获取多个键的值

func (*Client) Close added in v0.1.2

func (c *Client) Close() error

Close 关闭客户端

func (*Client) Del added in v0.1.2

func (c *Client) Del(ctx context.Context, key []byte) error

Del 删除缓存键

func (*Client) Get added in v0.1.2

func (c *Client) Get(ctx context.Context, key []byte) ([]byte, error)

Get 从缓存中获取值

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) GetTTL added in v0.1.2

func (c *Client) GetTTL(ctx context.Context, key []byte) (time.Duration, error)

GetTTL 获取键的剩余TTL

func (*Client) Set added in v0.1.2

func (c *Client) Set(ctx context.Context, key, value []byte) error

Set 设置缓存值

func (*Client) SetWithTTL added in v0.1.2

func (c *Client) SetWithTTL(ctx context.Context, key, value []byte, ttl time.Duration) error

SetWithTTL 设置带TTL的缓存值

func (*Client) Stats added in v0.1.2

func (c *Client) Stats(ctx context.Context) map[string]interface{}

Stats 返回缓存统计信息

func (*Client) WithContext added in v0.1.2

func (c *Client) WithContext(ctx context.Context) context.Context

WithContext 在上下文中嵌入当前客户端

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

func FromContext(ctx context.Context) *CtxCache

FromContext 从 ctx 中读取 CtxCache(若不存在返回 nil)

func NewCtxCache

func NewCtxCache(h Handler) *CtxCache

NewCtxCache 用现有的 Handler 创建 CtxCache

func (*CtxCache) BatchGet added in v0.1.2

func (c *CtxCache) BatchGet(keys [][]byte) ([][]byte, []error)

BatchGet 批量获取多个键的值

func (*CtxCache) Close

func (c *CtxCache) Close() error

Close 关闭底层 handler(如果底层实现需要关闭)

func (*CtxCache) Del

func (c *CtxCache) Del(ctx context.Context, key []byte) error

Del 删除键

func (*CtxCache) Get

func (c *CtxCache) Get(ctx context.Context, key []byte) ([]byte, error)

Get 直接从底层缓存读取

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) GetTTL added in v0.1.2

func (c *CtxCache) GetTTL(ctx context.Context, key []byte) (time.Duration, error)

GetTTL 获取键的剩余生存时间

func (*CtxCache) Set

func (c *CtxCache) Set(ctx context.Context, key, value []byte) error

Set 直接写入底层缓存(无 TTL)

func (*CtxCache) SetWithTTL

func (c *CtxCache) SetWithTTL(ctx context.Context, key, value []byte, ttl time.Duration) error

SetWithTTL 写入缓存并设置 TTL

func (*CtxCache) Stats added in v0.1.2

func (c *CtxCache) Stats() map[string]interface{}

Stats 返回缓存统计信息

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) Extend added in v0.1.2

func (l *DistributedLock) Extend(ctx context.Context, ttl time.Duration) error

Extend 延长锁的TTL

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

func (l *DistributedLock) LockWithTimeout(ctx context.Context, timeout time.Duration) error

LockWithTimeout 带超时的获取锁

func (*DistributedLock) TTL added in v0.1.2

TTL 获取锁的剩余TTL

func (*DistributedLock) TryLock added in v0.1.2

func (l *DistributedLock) TryLock(ctx context.Context) (bool, error)

TryLock 尝试获取锁(非阻塞)

func (*DistributedLock) Unlock added in v0.1.2

func (l *DistributedLock) Unlock(ctx context.Context) error

Unlock 释放锁

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) Close

func (h *ExpiringHandler) Close() error

Close 停止后台清理并释放资源

func (*ExpiringHandler) Del

func (h *ExpiringHandler) Del(key []byte) error

Del 删除键

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

func NewRedisHandler(cfg *redis.Options) (Handler, error)

NewRedisHandler 创建新的 RedisHandler

func NewRedisHandlerSimple added in v0.1.2

func NewRedisHandlerSimple(addr, password string, db int) (Handler, error)

NewRedisHandlerSimple 创建新的 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 设置所有值

func (*HotKeyCache[K, V]) Size added in v0.1.2

func (h *HotKeyCache[K, V]) Size(ctx context.Context) (int, error)

Size 获取缓存大小(直接从本地缓存计算,避免触发加载)

func (*HotKeyCache[K, V]) Stop added in v0.1.2

func (h *HotKeyCache[K, V]) Stop()

Stop 停止自动刷新

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 注册缓存

func (*HotKeyManager) StopAll added in v0.1.2

func (m *HotKeyManager) StopAll()

StopAll 停止所有自动刷新

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

func (g *IDGenerator) GenerateIDs(ctx context.Context, n int) ([]string, error)

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

func (g *IDGenerator) GetSequenceByTime(ctx context.Context, timePrefix string) (int64, error)

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) Close

func (h *LRUHandler) Close() error

Close 实现 Handler.Close

func (*LRUHandler) Del

func (h *LRUHandler) Del(key []byte) error

Del 实现 Handler.Del

func (*LRUHandler) Get

func (h *LRUHandler) Get(key []byte) ([]byte, error)

Get 实现 Handler.Get

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

func (m *LockManager) GetAllLockStats(ctx context.Context) (map[string]*LockStats, error)

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

type MessageHandler func(ctx context.Context, channel string, message string) error

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缓存失效

func (*MultiLevelCache[T]) Set added in v0.1.7

func (m *MultiLevelCache[T]) Set(ctx context.Context, key string, value T) error

Set 设置缓存到L1和L2

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) Close added in v0.1.2

func (p *PubSub) Close() error

Close 关闭发布订阅

func (*PubSub) GetChannels added in v0.1.2

func (p *PubSub) GetChannels() []string

GetChannels 获取已订阅的频道列表

func (*PubSub) GetStats added in v0.1.2

func (p *PubSub) GetStats() *PubSubStats

GetStats 获取统计信息

func (*PubSub) GetSubscribers added in v0.1.2

func (p *PubSub) GetSubscribers() int

GetSubscribers 获取活跃的订阅者数量

func (*PubSub) Publish added in v0.1.2

func (p *PubSub) Publish(ctx context.Context, channel string, message interface{}) error

Publish 发布消息

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

func (p *PubSub) Unsubscribe(channels ...string) error

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) Clear added in v0.1.2

func (q *QueueHandler) Clear(ctx context.Context, queueName string, queueType QueueType) error

Clear 清空队列

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

func (q *QueueHandler) ReleaseLock(ctx context.Context, queueName string, workerID string) error

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 QueueType added in v0.1.2

type QueueType string

QueueType 队列类型

const (
	QueueTypeFIFO     QueueType = "fifo"     // 先进先出队列
	QueueTypeLIFO     QueueType = "lifo"     // 后进先出队列(栈)
	QueueTypePriority QueueType = "priority" // 优先级队列
	QueueTypeDelayed  QueueType = "delayed"  // 延时队列
)

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) Close

func (h *RedisHandler) Close() error

Close 实现 Handler 接口的 Close 方法

func (*RedisHandler) Del

func (h *RedisHandler) Del(k []byte) error

Del 实现 Handler 接口的 Del 方法

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) Set

func (h *RedisHandler) Set(k, v []byte) error

Set 实现 Handler 接口的 Set 方法

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数据加载器

func (*SQLDataLoader[K, V]) Load added in v0.1.2

func (s *SQLDataLoader[K, V]) Load(ctx context.Context) (map[K]V, error)

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) Close

func (h *ShardedHandler) Close() error

Close 关闭所有 shard

func (*ShardedHandler) Del

func (h *ShardedHandler) Del(key []byte) error

Del 转发

func (*ShardedHandler) Get

func (h *ShardedHandler) Get(key []byte) ([]byte, error)

Get 转发

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) Close added in v0.1.7

func (c *SmartCache) Close() error

Close 关闭缓存

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 检查订阅是否活跃

func (*Subscriber) Stop added in v0.1.2

func (s *Subscriber) Stop()

Stop 停止订阅

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) Get

func (h *TwoLevelHandler) Get(key []byte) ([]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 返回两级缓存的统计信息

type TypedMessageHandler added in v0.1.2

type TypedMessageHandler[T any] func(ctx context.Context, channel string, message T) error

TypedMessageHandler 泛型消息处理器

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 高级使用示例

Jump to

Keyboard shortcuts

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