/
config_cache.go
69 lines (58 loc) · 1.65 KB
/
config_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
package configcat
import (
"sync"
)
// ConfigCache is a cache API used to make custom cache implementations.
type ConfigCache interface {
// Get reads the configuration from the cache.
Get() (string, error)
// Set writes the configuration into the cache.
Set(value string) error
}
type inMemoryConfigCache struct {
value string
}
// ConfigStore is used to maintain the cached configuration.
type ConfigStore struct {
cache ConfigCache
logger Logger
inMemoryValue string
sync.RWMutex
}
func newConfigStore(log Logger, cache ConfigCache) *ConfigStore {
return &ConfigStore{cache: cache, logger: log.Prefix("ConfigCat - Config Cache")}
}
// NewInMemoryConfigCache creates an in-memory cache implementation used to store the fetched configurations.
func NewInMemoryConfigCache() *inMemoryConfigCache {
return &inMemoryConfigCache{value: ""}
}
// Get reads the configuration from the cache.
func (cache *inMemoryConfigCache) Get() (string, error) {
return cache.value, nil
}
// Set writes the configuration into the cache.
func (cache *inMemoryConfigCache) Set(value string) error {
cache.value = value
return nil
}
// Get reads the configuration.
func (store *ConfigStore) Get() string {
store.RLock()
defer store.RUnlock()
value, err := store.cache.Get()
if err != nil {
store.logger.Printf("Reading from the cache failed, %s", err)
return store.inMemoryValue
}
return value
}
// Set writes the configuration.
func (store *ConfigStore) Set(value string) {
store.Lock()
defer store.Unlock()
store.inMemoryValue = value
err := store.cache.Set(value)
if err != nil {
store.logger.Printf("Saving into the cache failed, %s", err)
}
}