added method for finding cache key age

This commit is contained in:
Radu Ioan Fericean
2013-12-15 20:43:46 +02:00
parent aa2360f756
commit 609f6271df
2 changed files with 41 additions and 0 deletions

View File

@@ -11,6 +11,7 @@ import (
type expiringCacheEntry interface {
XCache(key string, expire time.Duration, value expiringCacheEntry)
timer() *time.Timer
age() time.Duration
KeepAlive()
}
@@ -70,6 +71,11 @@ func (xe *XEntry) timer() *time.Timer {
return xe.t
}
func (xe *XEntry) age() time.Duration {
return time.Since(xe.timestamp)
}
// Mark entry to be kept another expirationDuration period
func (xe *XEntry) KeepAlive() {
xe.Lock()
@@ -105,6 +111,24 @@ func GetCached(key string) (v interface{}, err error) {
return nil, errors.New("not found")
}
func GetKeyAge(key string) (time.Duration, error) {
mux.RLock()
defer mux.RUnlock()
if r, ok := cache[key]; ok {
return time.Since(r.timestamp), nil
}
return 0, errors.New("not found")
}
func GetXKeyAge(key string) (time.Duration, error) {
xMux.RLock()
defer xMux.RUnlock()
if r, ok := xcache[key]; ok {
return r.age(), nil
}
return 0, errors.New("not found")
}
func RemKey(key string) {
mux.Lock()
defer mux.Unlock()

View File

@@ -96,3 +96,20 @@ func TestXRemKey(t *testing.T) {
t.Error("Error removing xcached key: ", err, t1)
}
}
func TestGetKeyAge(t *testing.T) {
Cache("t1", "test")
d, err := GetKeyAge("t1")
if err != nil || d > time.Millisecond || d < time.Nanosecond {
t.Error("Error getting cache key age: ", d)
}
}
func TestXGetKeyAge(t *testing.T) {
a := &myStruct{data: "mama are mere"}
a.XCache("t1", 10*time.Second, a)
d, err := GetXKeyAge("t1")
if err != nil || d > time.Millisecond || d < time.Nanosecond {
t.Error("Error getting cache key age: ", d)
}
}