-
Notifications
You must be signed in to change notification settings - Fork 0
/
k6namedCacheOperator.go
56 lines (47 loc) · 1.45 KB
/
k6namedCacheOperator.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
package k6cache
import (
"fmt"
"time"
"github.com/patrickmn/go-cache"
)
func (k6cache *K6Cache) CreateWithExpiryInSeconds(name string, durationInSeconds int) {
if k6cache.caches == nil {
k6cache.caches = make(map[string]*cache.Cache)
}
namedCache := k6cache.caches[name]
duration := time.Duration(durationInSeconds) * time.Second
if namedCache == nil {
namedCache = cache.New(duration, duration)
k6cache.caches[name] = namedCache
}
}
func (k6cache *K6Cache) PutToNamedCache(name string, key string, value string) error {
namedCache := k6cache.caches[name]
if err := validateCacheExistence(name, namedCache); err != nil {
return err
}
namedCache.Set(key, value, cache.DefaultExpiration)
return nil
}
func (k6cache *K6Cache) GetFromNamedCache(name string, key string) (interface{}, error) {
namedCache := k6cache.caches[name]
if err := validateCacheExistence(name, namedCache); err != nil {
return nil, err
}
stringValue, _ := namedCache.Get(key)
return stringValue, nil
}
func (k6cache *K6Cache) RemoveFromNamedCache(name string, key string) error {
namedCache := k6cache.caches[name]
if err := validateCacheExistence(name, namedCache); err != nil {
return err
}
namedCache.Delete(key)
return nil
}
func validateCacheExistence(name string, namedCache *cache.Cache) error {
if namedCache == nil {
return fmt.Errorf("Cache with name %s was not created, execute `createWithExpiryInSeconds(\"%s\", <expiry>)` first", name, name)
}
return nil
}