-
Notifications
You must be signed in to change notification settings - Fork 35
/
cache.go
70 lines (57 loc) · 1.19 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
70
package util
import (
// "fmt"
"sync"
"time"
)
//过期时间 10小时
const Time int64 = 1 //3600 * 10
//动态缓存数据库
var Caches *CacheManager
type CacheManager struct {
lock *sync.RWMutex
caches map[string]*Cache
}
type Cache struct {
Value interface{}
Times int64
}
func Init() {
Caches = NewCacheManager(300)
}
func NewCacheManager(size int) *CacheManager {
return &CacheManager{new(sync.RWMutex), make(map[string]*Cache, size)}
}
func (this *CacheManager) Set(key string, v interface{}) {
this.lock.Lock()
x := Cache{Value: v, Times: Time}
this.caches[key] = &x
this.lock.Unlock()
}
func (this *CacheManager) Get(key string) *Cache {
this.lock.RLock()
v := this.caches[key]
this.lock.RUnlock()
return v
}
func (this *CacheManager) Delete(key string) *Cache {
this.lock.Lock()
v := this.caches[key]
delete(this.caches, key)
this.lock.Unlock()
return v
}
func (this *CacheManager) IsExist(key string) bool {
if xy := this.Get(key); xy != nil {
return true
} else {
return false
}
}
func (this *CacheManager) IsExpired(key string, ttl int) bool {
if xy := this.Get(key); xy != nil {
return (time.Now().Unix() - xy.Times) >= int64(ttl)
} else {
return true
}
}