# GoCache **Repository Path**: sheeplight/go-cache ## Basic Information - **Project Name**: GoCache - **Description**: 泛用性极强的缓存工厂 - **Primary Language**: Go - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-10-06 - **Last Updated**: 2025-10-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # GoCache 一个高性能的Go缓存库,支持多种缓存策略和类型。 ## ✨ 特性 - ⏰ **TTL支持**:精确的过期时间管理,支持纳秒级精度 - 🎯 **泛型支持**:支持任意可比较的键类型和值类型 - 🔄 **时间轮算法**:高效的时间索引,O(1)插入和删除 - 📊 **统计信息**:实时命中率、未命中、淘汰统计 - 🛡️ **并发安全**:高并发场景下的优秀性能表现 - 🎨 **工厂模式**:统一的接口设计,易于扩展 - 🚀 **高性能**:基于sync.Map和原子操作,优秀的读写性能 ## 🏗️ 架构设计 ``` GoCache ├── Cache Interface # 统一缓存接口 ├── CacheFactory # 缓存工厂 └── Implementations ├── LockFreeTTLCache # TTL缓存实现 └── [Future] LRUCache # 计划中的LRU缓存 └── [Future] LFUCache # 计划中的LFU缓存 ``` ## 🚀 快速开始 ### 安装 ```bash go get gitee.com/sheeplight/go-cache ``` ### 基本使用 ```go package main import ( "fmt" "time" "gitee.com/sheeplight/go-cache/gocache" ) func main() { // 创建TTL缓存 cache := gocache.NewTTLCache[string, string](1000) defer cache.StopCleanup() // 启动自动清理 cache.StartCleanup() // 设置永久数据(TTL = 0) cache.Set("config", "production", 0) // 设置临时数据 cache.Set("session", "abc123", 30*time.Minute) // 读取数据 if value, err := cache.Get("config"); err == nil { fmt.Printf("Config: %s\n", value) } // 删除数据 if err := cache.Del("session"); err == nil { fmt.Println("Session deleted") } // 获取统计信息 stats := cache.Stats() fmt.Printf("命中率: %.2f%%\n", stats.HitRate*100) } ``` ## 📚 API 文档 ### 缓存接口 ```go type Cache[K comparable, V any] interface { Set(key K, value V, ttl time.Duration) error Get(key K) (V, error) Del(key K) error Clear() (uint64, error) StartCleanup() StopCleanup() Stats() CacheStats } ``` **参数说明**: - `ttl = 0`:永不过期 - `ttl > 0`:指定过期时间 ### 工厂方法 ```go // 创建缓存实例 cache := gocache.NewTTLCache[string, string](maxSize) ``` ## 🎯 使用场景 ### ✅ 适合的场景 - **读多写少**:90%以上是读操作 - **会话管理**:用户会话、登录状态 - **API缓存**:接口响应缓存 - **配置缓存**:系统配置信息 - **高并发服务**:微服务、API网关 ### ❌ 不适合的场景 - **频繁写入**:写操作比例过高 - **频繁删除**:大量删除操作 - **长TTL**:TTL超过1天的场景 - **内存敏感**:对内存使用要求极高 ## ⚡ 性能表现 基于Intel i7-9750H的基准测试结果: ``` BenchmarkSimpleSet-12 10000 320308 ns/op 26859 B/op 10 allocs/op BenchmarkSimpleGet-12 9242786 127.9 ns/op 13 B/op 1 allocs/op BenchmarkSimpleTTL-12 21432 65825 ns/op 295 B/op 6 allocs/op BenchmarkConcurrentGet-12 29998447 38.99 ns/op 13 B/op 1 allocs/op ``` - **读取性能**:~128ns/op(单线程),~39ns/op(并发) - **写入性能**:~320μs/op(普通),~66μs/op(TTL) - **内存效率**:最小化内存分配和GC压力 ## 🔧 高级功能 ### 会话管理示例 ```go type SessionManager struct { cache gocache.TTLCache[string, *UserSession] } type UserSession struct { UserID string Username string LoginTime time.Time LastSeen time.Time } func NewSessionManager() *SessionManager { cache := gocache.NewTTLCache[string, *UserSession](10000) cache.StartCleanup() return &SessionManager{cache: cache} } func (sm *SessionManager) CreateSession(sessionID string, user *UserSession, ttl time.Duration) error { user.LastSeen = time.Now() return sm.cache.Set(sessionID, user, ttl) } func (sm *SessionManager) GetSession(sessionID string) (*UserSession, error) { session, err := sm.cache.Get(sessionID) if err != nil { return nil, err } // 更新最后访问时间 session.LastSeen = time.Now() sm.cache.Set(sessionID, session, 30*time.Minute) return session, nil } ``` ### 配置缓存示例 ```go type ConfigCache struct { cache gocache.Cache[string, interface{}] } func NewConfigCache() *ConfigCache { return &ConfigCache{ cache: gocache.NewCache[string, interface{}](), } } func (cc *ConfigCache) SetConfig(key string, value interface{}) { cc.cache.Set(key, value, 0) // 永不过期 } func (cc *ConfigCache) GetConfig(key string) (interface{}, error) { return cc.cache.Get(key) } ``` ## 🛠️ 技术实现 ### 高性能设计 - 使用`sync.Map`的原子操作 - 时间轮使用细粒度锁 - CAS操作处理并发更新 ### 时间轮算法 - 分层时间轮设计(4层) - 自动选择合适的时间精度 - O(1)时间复杂度的插入和删除 ### 内存管理 - 智能的容量限制 - 自动淘汰过期数据 - 最小化内存碎片 ## 🚧 开发计划 - [ ] **LRU缓存**:基于最近最少使用算法的缓存 - [ ] **LFU缓存**:基于最少使用频率算法的缓存 - [ ] **分布式缓存**:支持Redis等外部存储 - [ ] **缓存预热**:启动时预加载数据 - [ ] **监控指标**:更详细的性能指标 - [ ] **配置优化**:可配置的清理策略 ## 📄 许可证 本项目采用 MIT 许可证。详见 [LICENSE](LICENSE) 文件。 ## 🤝 贡献 欢迎提交 Issue 和 Pull Request! 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request ## 📞 联系方式 - 项目地址:[gitee.com/sheeplight/go-cache](https://gitee.com/sheeplight/go-cache) - 问题反馈:[Issues](https://gitee.com/sheeplight/go-cache/issues) --- ⭐ 如果这个项目对你有帮助,请给它一个星标!