added Fetch method to get + set on miss
This commit is contained in:
parent
751266c34a
commit
ba89971ba8
2 changed files with 8 additions and 30 deletions
|
@ -1,30 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"ccache"
|
||||
)
|
||||
|
||||
func main() {
|
||||
c := ccache.New(ccache.Configure().PromoteDelay(time.Second * 0))
|
||||
fmt.Println(c.Get("abc"))
|
||||
c.Set("abc", new("xxx"))
|
||||
fmt.Println(c.Get("abc"))
|
||||
time.Sleep(time.Second)
|
||||
fmt.Println(c.Get("abc"))
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
value string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
func (i *Item) Expires() time.Time {
|
||||
return i.expires
|
||||
}
|
||||
|
||||
func new(value string) *Item {
|
||||
return &Item{value, time.Now().Add(time.Minute)}
|
||||
}
|
8
cache.go
8
cache.go
|
@ -51,6 +51,14 @@ func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
|
|||
c.promote(item)
|
||||
}
|
||||
|
||||
func (c *Cache) Fetch(key string, duration time.Duration, fetch func() interface{}) interface{} {
|
||||
item := c.Get(key)
|
||||
if item != nil { return item }
|
||||
value := fetch()
|
||||
c.Set(key, value, duration)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c *Cache) Delete(key string) {
|
||||
item := c.bucket(key).getAndDelete(key)
|
||||
if item != nil {
|
||||
|
|
Loading…
Reference in a new issue