Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add entry expiration example to doc #32

Merged
merged 1 commit into from
Jun 9, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,43 @@ func main() {
Get: ok
```

### Manually set a key-value pair, with an expiration time.

```go
package main

import (
"github.com/bluele/gcache"
"fmt"
"time"
)

func main() {
gc := gcache.New(20).
LRU().
Build()
gc.SetWithExpire("key", "ok", time.Second*10)
value, _ := gc.Get("key")
fmt.Println("Get:", value)

// Wait for value to expire
time.Sleep(time.Second*10)

value, err = gc.Get("key")
if err != nil {
panic(err)
}
fmt.Println("Get:", value)
}
```

```
Get: ok
// 10 seconds later, new attempt:
panic: ErrKeyNotFound
```


### Automatically load value

```go
Expand Down Expand Up @@ -78,6 +115,48 @@ func main() {
Get: ok
```

### Automatically load value with expiration

```go
package main

import (
"github.com/bluele/gcache"
"fmt"
)

func main() {
gc := gcache.New(20).
LRU().
LoaderExpireFunc(func(key interface{}) (interface{}, *time.Duration, error) {
expire := 1 * time.Second
return "ok", &expire, nil
}).
EvictedFunc(func(key, value interface{}) {
fmt.Println("evicted key:", key)
}).
Build()
value, err := gc.Get("key")
if err != nil {
panic(err)
}
fmt.Println("Get:", value)
time.Sleep(1 * time.Second)
value, err := gc.Get("key")
if err != nil {
panic(err)
}
fmt.Println("Get:", value)
}
```

```
Get: ok
evicted key: key
Get: ok
```


## Cache Algorithm

* Least-Frequently Used (LFU)
Expand Down