Hello

date
Feb 26, 2020
updateDate
slug
hello
status
Published
tags
summary
type
Post
world
 
图片 block
notion image
code block
package cache import ( "math/rand" "sync" "time" ) type Cache struct { sync.Map } type entry struct { ttl time.Time value interface{} } func New() *Cache { return &Cache{ Map: sync.Map{}, } } func (c *Cache) Get(key string) (result interface{}, ok bool) { if ele, hit := c.Load(key); hit { if time.Now().After(ele.(*entry).ttl) { c.Delete(key) return } return ele.(*entry).value, true } return } func (c *Cache) Set(key string, value interface{}, ttl time.Duration) { c.Store(key, &entry{ ttl: time.Now().Add(ttl), value: value, }) } var c *Cache func init() { c = New() } func Wrap[T any](key string, fn func() (T, error), ttl time.Duration) (value T, err error) { if v, ok := c.Get(key); ok { value = v.(T) return } value, err = fn() if err != nil { return } c.Set(key, value, ttl) return }
 
table block
1
2
7
3
4
8
5
6
9
 

© Zzde 2020 - 2024