Files
bj_power/bj_power_mes/internal/logic/cache.go
T

54 lines
1.4 KiB
Go
Raw Normal View History

package logic
import (
"sync"
"time"
"golang.org/x/sync/singleflight"
)
// memCache 进程内 TTL 缓存:
// MES 为单机单实例部署,看板缓存无需跨进程共享,内存缓存等价替代且少一个外部依赖。
// 防击穿:singleflight 保证同一 key 并发重建只放行一个,其余调用方共享同一份结果
// (无需手写重试循环,也不依赖任何外部服务)。
type memCache struct {
mu sync.Mutex
items map[string]*memItem
sf singleflight.Group
}
type memItem struct {
value any
expire time.Time
}
// dashboardCache 看板缓存唯一实例(dashboard:snapshot / dashboard:front 两个 key)。
var dashboardCache = &memCache{items: make(map[string]*memItem)}
// getOrBuild 命中未过期直接返回缓存值;否则经 singleflight 重建并写回。
// build 返回错误时不写缓存,下次请求重试。
func (c *memCache) getOrBuild(key string, ttl time.Duration, build func() (any, error)) (any, error) {
c.mu.Lock()
if it, ok := c.items[key]; ok && time.Now().Before(it.expire) {
v := it.value
c.mu.Unlock()
return v, nil
}
c.mu.Unlock()
v, err, _ := c.sf.Do(key, func() (any, error) {
val, e := build()
if e != nil {
return nil, e
}
c.mu.Lock()
c.items[key] = &memItem{value: val, expire: time.Now().Add(ttl)}
c.mu.Unlock()
return val, nil
})
if err != nil {
return nil, err
}
return v, nil
}