-
Notifications
You must be signed in to change notification settings - Fork 0
/
goks.go
101 lines (87 loc) · 1.73 KB
/
goks.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
package goks
import (
"goks/algo"
"goks/algo/lru"
"goks/cache"
"sync"
)
// Cache ...
type Cache struct {
sync.RWMutex
repo algo.Repository
}
func NewClient(options ...*cache.Option) (c cache.CacheRepository) {
option := mergeCacheOptions(options...)
if option.MaxSizeItem == 0 {
// if not set use default size
option.MaxSizeItem = cache.DefaultCapacity
}
c = &Cache{
repo: NewCacheRepository(*option),
}
return c
}
func NewCacheOptions() (op *cache.Option) {
return &cache.Option{}
}
func NewCacheRepository(option cache.Option) algo.Repository {
var cacheRepo algo.Repository
cacheRepo = lru.NewLruCache(option.MaxSizeItem)
return cacheRepo
}
func mergeCacheOptions(options ...*cache.Option) (opts *cache.Option) {
opts = new(cache.Option)
// Check given option
for _, op := range options {
if op.MaxSizeItem != 0 {
opts.MaxSizeItem = op.MaxSizeItem
}
}
return
}
func (c *Cache) Set(key string, value interface{}) error {
topic := &cache.Topic{
Key: key,
Value: value,
}
c.Lock()
err := c.repo.Set(topic)
if err != nil {
return err
}
c.Unlock()
return nil
}
func (c *Cache) Get(key string) (val interface{}, err error) {
c.RLock()
topic, err := c.repo.Get(key)
c.RUnlock()
if err != nil {
return
}
return topic.Value, nil
}
func (c *Cache) Delete(key string) (err error) {
panic("implement me")
}
func (c *Cache) GetKeys() (keys []string, err error) {
c.RLock()
keys, err = c.repo.GetKeys()
if err != nil {
return
}
c.RUnlock()
return
}
func (c *Cache) ClearCache() (err error) {
panic("implement me")
}
func (c *Cache) PeekByKey(key string) (val interface{}, err error) {
c.RLock()
topic, err := c.repo.Peek(key)
if err != nil {
return nil, err
}
c.RUnlock()
return topic, nil
}