package main
import (
"fmt"
"sync"
"time"
)
type ExpiringMap struct {
data map[string]Item
mu sync.Mutex
}
type Item struct {
Value interface{}
Expiration int64
}
func NewExpiringMap() *ExpiringMap {
return &ExpiringMap{
data: make(map[string]Item),
}
}
func (em *ExpiringMap) Set(key string, value interface{}, duration time.Duration) {
em.mu.Lock()
defer em.mu.Unlock()
em.data[key] = Item{
Value: value,
Expiration: time.Now().Add(duration).UnixNano(),
}
}
func (em *ExpiringMap) Get(key string) (interface{}, bool) {
em.mu.Lock()
defer em.mu.Unlock()
item, found := em.data[key]
if !found {
return nil, false
}
if time.Now().UnixNano() > item.Expiration {
delete(em.data, key)
return nil, false
}
return item.Value, true
}
func (em *ExpiringMap) Delete(key string) {
em.mu.Lock()
defer em.mu.Unlock()
delete(em.data, key)
}
func main() {
expiringMap := NewExpiringMap()
expiringMap.Set("foo", "bar", 5*time.Second)
value, found := expiringMap.Get("foo")
if found {
fmt.Println("Found:", value)
} else {
fmt.Println("Not found")
}
time.Sleep(6 * time.Second)
value, found = expiringMap.Get("foo")
if found {
fmt.Println("Found:", value)
} else {
fmt.Println("Not found")
}
}
golang构造带失效时间的map
最新推荐文章于 2024-07-08 19:15:16 发布