git-subtree-dir: server git-subtree-mainline:c4e617ada7git-subtree-split:e64421295f
43 lines
798 B
Go
43 lines
798 B
Go
package agent
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// 通用 TTL 缓存:天气结果(*WeatherResult)、CPS 转链(string)等均可复用
|
|
type cacheEntry struct {
|
|
data any
|
|
expiresAt time.Time
|
|
}
|
|
|
|
type Cache struct {
|
|
mu sync.Mutex
|
|
ttl time.Duration
|
|
items map[string]cacheEntry
|
|
}
|
|
|
|
func NewTTLCache(ttl time.Duration) *Cache {
|
|
return &Cache{ttl: ttl, items: make(map[string]cacheEntry)}
|
|
}
|
|
|
|
func (c *Cache) Get(key string) (any, bool) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
e, ok := c.items[key]
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
if time.Now().After(e.expiresAt) {
|
|
delete(c.items, key)
|
|
return nil, false
|
|
}
|
|
return e.data, true
|
|
}
|
|
|
|
func (c *Cache) Set(key string, data any) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.items[key] = cacheEntry{data: data, expiresAt: time.Now().Add(c.ttl)}
|
|
}
|