-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
89 lines (76 loc) · 1.74 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package database
import (
"errors"
"time"
"github.com/Nerv-Core-Developers/nerv-provider-golang/shared"
cache "github.com/patrickmn/go-cache"
)
type DBcache struct {
Name string
DataDir string
ExpTime time.Duration
CleanInterval time.Duration
DB *cache.Cache
Logger shared.LoggerInterface
}
func (db *DBcache) Delete(key string) error {
if db.isOpen() {
return errors.New("init db first")
}
db.DB.Delete(key)
return nil
}
func (db *DBcache) Get(key string) (interface{}, int, error) {
if db.isOpen() {
return nil, 0, errors.New("init db first")
}
if value, ttl, exist := db.DB.GetWithExpiration(key); exist {
return value, ttl.Minute(), nil
}
return nil, 0, errors.New("key not exist")
}
func (db *DBcache) Put(key string, value interface{}, timeout int, overwrite bool) error {
if db.isOpen() {
return errors.New("init db first")
}
if overwrite {
if _, ok := db.DB.Get(key); ok {
return errors.New("key already exist")
}
db.DB.Set(key, value, time.Duration(timeout)*time.Second)
} else {
db.DB.Set(key, value, time.Duration(timeout)*time.Second)
}
return nil
}
func (db *DBcache) Export(des string) error {
if db.isOpen() {
return errors.New("init db first")
}
return nil
}
func (db *DBcache) Load(src string) error {
if db.DB == nil {
return errors.New("init db first")
}
return nil
}
func (db *DBcache) Init(dbname string, dbpath string) error {
db.Name = dbname
db.DataDir = dbpath + "/" + dbname
db.DB = cache.New(db.ExpTime, db.CleanInterval)
return nil
}
func (db *DBcache) Close() error {
db.DB = nil
return nil
}
func (db *DBcache) isOpen() bool {
if db.DB != nil {
return true
}
return false
}
func (db *DBcache) Batch([]shared.DBPatch) error {
return nil
}