Hello
date
Feb 26, 2020
updateDate
slug
hello
status
Published
tags
summary
type
Post
world
图片 block
![notion image](https://www.notion.so/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F2b68d630-3bbd-4836-b798-c0e912e385c8%2F4df0eb7aeafafc6d8c46fcf2cfc578b1.png?table=block&id=9be3470e-c3c0-40b0-8702-7d93cd4dede4&cache=v2)
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 |