replace on layeredcache

This commit is contained in:
Karl Seguin
2014-11-13 22:23:52 +07:00
parent 65573a0cb6
commit 7316f99bd9
3 changed files with 26 additions and 4 deletions

View File

@@ -35,6 +35,16 @@ func (b *LayeredBucket) set(primary, secondary string, value interface{}, durati
return item, new
}
func (b *LayeredBucket) replace(primary, secondary string, value interface{}) bool {
b.Lock()
bucket, exists := b.buckets[primary]
b.Unlock()
if exists == false {
return false
}
return bucket.replace(secondary, value)
}
func (b *LayeredBucket) delete(primary, secondary string) *Item {
b.RLock()
bucket, exists := b.buckets[primary]

View File

@@ -65,6 +65,10 @@ func (c *LayeredCache) Set(primary, secondary string, value interface{}, duratio
}
}
func (c *LayeredCache) Replace(primary, secondary string, value interface{}) bool {
return c.bucket(primary).replace(primary, secondary, value)
}
func (c *LayeredCache) Fetch(primary, secondary string, duration time.Duration, fetch func() (interface{}, error)) (interface{}, error) {
item := c.Get(primary, secondary)
if item != nil {

View File

@@ -39,6 +39,18 @@ func (l *LayeredCacheTests) SetsMultipleValueWithinTheSameLayer() {
Expect(cache.Get("baron", "friend")).To.Equal(nil)
}
func (l *LayeredCacheTests) ReplaceDoesNothingIfKeyDoesNotExist() {
cache := newLayered()
Expect(cache.Replace("spice", "flow", "value-a")).To.Equal(false)
}
func (l *LayeredCacheTests) ReplaceUpdatesTheValue() {
cache := newLayered()
cache.Set("spice", "flow", "value-a", time.Minute)
Expect(cache.Replace("spice", "flow", "value-b")).To.Equal(true)
Expect(cache.Get("spice", "flow").Value().(string)).To.Equal("value-b")
}
func (l *LayeredCacheTests) DeletesAValue() {
cache := newLayered()
cache.Set("spice", "flow", "value-a", time.Minute)
@@ -125,10 +137,6 @@ func (c *LayeredCacheTests) RemovesOldestItemWhenFull() {
Expect(cache.Get("xx", "b").Value()).To.Equal(9001)
}
// func (c *LayeredCacheTests) GetsAnExpiredIten() {
// }
func newLayered() *LayeredCache {
return Layered(Configure())
}