-
Notifications
You must be signed in to change notification settings - Fork 11
/
cache.go
57 lines (49 loc) · 960 Bytes
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package go_ernie
import (
"sync"
"time"
)
type Cache struct {
data map[string]cacheItem
lock sync.RWMutex
}
type cacheItem struct {
value interface{}
expiration time.Time
}
func NewCache() *Cache {
return &Cache{
data: make(map[string]cacheItem),
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
item, exists := c.data[key]
if !exists {
return nil, false
}
// 检查过期时间
if time.Now().After(item.expiration) {
// 过期了,从缓存中删除该项
delete(c.data, key)
return nil, false
}
return item.value, true
}
func (c *Cache) Set(key string, value interface{}, expiration time.Duration) {
c.lock.Lock()
defer c.lock.Unlock()
c.data[key] = cacheItem{
value: value,
expiration: time.Now().Add(expiration),
}
}
func (c *Cache) Del(key string) {
c.lock.Lock()
defer c.lock.Unlock()
_, exists := c.data[key]
if exists {
delete(c.data, key)
}
}