-
Notifications
You must be signed in to change notification settings - Fork 13
/
cacher.go
103 lines (84 loc) · 2.44 KB
/
cacher.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package cacher
import (
"fmt"
"github.com/muharihar/d3ta-go/system/cacher/adapter"
)
// CacherType Represent CacherType
type CacherType string
const (
MemoryCacher CacherType = "memory"
FileCacher CacherType = "file"
RedisCacher CacherType = "redis"
MemcacheCacher CacherType = "memcache"
PGCacher CacherType = "postgres"
MyCacher CacherType = "mysql"
LedisCacher CacherType = "ledis"
NoDBCacher CacherType = "nodb"
)
// NewCacher create new Cacher
func NewCacher(cacherType CacherType, cacherEngine adapter.ICacherEngine) (*Cacher, error) {
if cacherEngine == nil {
return nil, fmt.Errorf("Invalid cacherEngine value")
}
c := Cacher{
_type: cacherType,
cacherEngine: cacherEngine,
}
// C4 prefix key
c.Context = "defaultContext"
c.Container = "defaultContainer"
c.Component = "defaultComponent"
return &c, nil
}
// Cacher type
type Cacher struct {
_type CacherType
cacherEngine adapter.ICacherEngine
Context string
Container string
Component string
}
// GetEngine get default Engine
func (c *Cacher) GetEngine() interface{} {
return c.cacherEngine.GetEngine()
}
// IsExist check if key is exist
func (c *Cacher) IsExist(key string) bool {
_key := fmt.Sprintf("%s.%s.%s.%s", c.Context, c.Container, c.Component, key)
return c.cacherEngine.IsExist(_key)
}
// Put put key value with timeout
func (c *Cacher) Put(key string, val interface{}, timeout int64) error {
_key := fmt.Sprintf("%s.%s.%s.%s", c.Context, c.Container, c.Component, key)
return c.cacherEngine.Put(_key, val, timeout)
}
// Get key value
func (c *Cacher) Get(key string) interface{} {
if !c.IsExist(key) {
return nil
}
_key := fmt.Sprintf("%s.%s.%s.%s", c.Context, c.Container, c.Component, key)
return c.cacherEngine.Get(_key)
}
// Incr increment key value
func (c *Cacher) Incr(key string) error {
_key := fmt.Sprintf("%s.%s.%s.%s", c.Context, c.Container, c.Component, key)
return c.cacherEngine.Incr(_key)
}
// Decr Decrement key value
func (c *Cacher) Decr(key string) error {
_key := fmt.Sprintf("%s.%s.%s.%s", c.Context, c.Container, c.Component, key)
return c.cacherEngine.Decr(_key)
}
// Delete delete existing key value
func (c *Cacher) Delete(key string) error {
if !c.IsExist(key) {
return nil
}
_key := fmt.Sprintf("%s.%s.%s.%s", c.Context, c.Container, c.Component, key)
return c.cacherEngine.Delete(_key)
}
// Flush deletes all cached data
func (c *Cacher) Flush() error {
return c.cacherEngine.Flush()
}