1 // key_value_cache provides an extremely simple string key to value cache.
2 // This is used to reduce the number of lookups from MySQL filename
3 // to the equivalent table or logical name given the conversion
4 // routines to do this use many regexps and this is quite expensive.
5 package key_value_cache
10 "github.com/sjmudd/pstop/lib"
13 // provide a mapping from filename to table.schema etc
14 type KeyValueCache struct {
15 cache map[string]string
16 read_requests, served_from_cache, write_requests int
19 // Create a new KeyValueCache entry.
20 func NewKeyValueCache() KeyValueCache {
21 lib.Logger.Println("KeyValueCache()")
23 return KeyValueCache{}
26 // Given a lookup key return the value if found.
27 func (kvc *KeyValueCache) Get(key string) (result string, err error) {
28 lib.Logger.Println("KeyValueCache.Get(", key, ")")
30 lib.Logger.Println("KeyValueCache.Get() kvc.cache is empty so enabling it")
31 kvc.cache = make(map[string]string)
33 kvc.served_from_cache = 0
34 kvc.write_requests = 0
39 if result, ok := kvc.cache[key]; ok {
40 kvc.served_from_cache++
41 lib.Logger.Println("Found: read_requests/servced_from_cache:", kvc.read_requests, kvc.served_from_cache)
44 lib.Logger.Println("Not found: read_requests/served_from_cache:", kvc.read_requests, kvc.served_from_cache)
45 return "", errors.New("Not found")
49 // Write to cache and return the value saved.
50 func (kvc *KeyValueCache) Put(key, value string) string {
51 lib.Logger.Println("KeyValueCache.Put(", key, ",", value, ")")
52 kvc.cache[key] = value
56 // Provide some staticts on read and write requests and the number
57 // of requests served from cache.
58 func (kvc *KeyValueCache) Statistics() (int, int, int) {
59 return kvc.read_requests, kvc.served_from_cache, kvc.write_requests