1 Star 1 Fork 1

xiaoyutab/xgotool

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cache.go 1.45 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyutab 提交于 2026-06-11 14:11 +08:00 . feat(https): slog日志改造 + 性能优化
package https
import (
"sync"
"time"
)
// 内建缓存组件(带容量上限的 LRU)
// 当缓存项数量超过 maxSize 时,自动淘汰最旧的条目。
type cache struct {
sync.Map
order []string // 按插入顺序记录 key,用于 LRU 淘汰
maxSize int // 最大缓存条目数,默认 10000
mu sync.Mutex // 保护 order 切片并发访问
}
// newCache 创建带容量上限的缓存实例。
func newCache(maxSize int) *cache {
if maxSize <= 0 {
maxSize = 10000
}
return &cache{
maxSize: maxSize,
order: make([]string, 0, maxSize),
}
}
// 获取缓存的值
//
// name 缓存名称
func (c *cache) Get(name string) string {
if v, ok := c.Load(name); ok {
if str, ok := v.(string); ok {
return str
}
}
return ""
}
// 设置缓存项的值
//
// name 设置项名称
// val 缓存项的值
// t 缓存时间 -/0-不缓存
func (c *cache) Set(name string, val string, t time.Duration) {
if t <= 0 {
return
}
// 容量超限时淘汰最旧条目
c.mu.Lock()
if c.maxSize > 0 && len(c.order) >= c.maxSize {
if old := c.order[0]; old != "" {
c.Delete(old)
}
c.order = c.order[1:]
}
c.order = append(c.order, name)
c.mu.Unlock()
c.Store(name, val)
go func(name string, t time.Duration) {
time.Sleep(t)
c.Delete(name)
c.mu.Lock()
for i, k := range c.order {
if k == name {
c.order = append(c.order[:i], c.order[i+1:]...)
break
}
}
c.mu.Unlock()
}(name, t)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xiaoyutab/xgotool.git
git@gitee.com:xiaoyutab/xgotool.git
xiaoyutab
xgotool
xgotool
v0.4.2

搜索帮助