...
1# go-cache
2
3go-cache is an in-memory key:value store/cache similar to memcached that is
4suitable for applications running on a single machine. Its major advantage is
5that, being essentially a thread-safe `map[string]interface{}` with expiration
6times, it doesn't need to serialize or transmit its contents over the network.
7
8Any object can be stored, for a given duration or forever, and the cache can be
9safely used by multiple goroutines.
10
11Although go-cache isn't meant to be used as a persistent datastore, the entire
12cache can be saved to and loaded from a file (using `c.Items()` to retrieve the
13items map to serialize, and `NewFrom()` to create a cache from a deserialized
14one) to recover from downtime quickly. (See the docs for `NewFrom()` for caveats.)
15
16### Installation
17
18`go get github.com/patrickmn/go-cache`
19
20### Usage
21
22```go
23import (
24 "fmt"
25 "github.com/patrickmn/go-cache"
26 "time"
27)
28
29func main() {
30 // Create a cache with a default expiration time of 5 minutes, and which
31 // purges expired items every 10 minutes
32 c := cache.New(5*time.Minute, 10*time.Minute)
33
34 // Set the value of the key "foo" to "bar", with the default expiration time
35 c.Set("foo", "bar", cache.DefaultExpiration)
36
37 // Set the value of the key "baz" to 42, with no expiration time
38 // (the item won't be removed until it is re-set, or removed using
39 // c.Delete("baz")
40 c.Set("baz", 42, cache.NoExpiration)
41
42 // Get the string associated with the key "foo" from the cache
43 foo, found := c.Get("foo")
44 if found {
45 fmt.Println(foo)
46 }
47
48 // Since Go is statically typed, and cache values can be anything, type
49 // assertion is needed when values are being passed to functions that don't
50 // take arbitrary types, (i.e. interface{}). The simplest way to do this for
51 // values which will only be used once--e.g. for passing to another
52 // function--is:
53 foo, found := c.Get("foo")
54 if found {
55 MyFunction(foo.(string))
56 }
57
58 // This gets tedious if the value is used several times in the same function.
59 // You might do either of the following instead:
60 if x, found := c.Get("foo"); found {
61 foo := x.(string)
62 // ...
63 }
64 // or
65 var foo string
66 if x, found := c.Get("foo"); found {
67 foo = x.(string)
68 }
69 // ...
70 // foo can then be passed around freely as a string
71
72 // Want performance? Store pointers!
73 c.Set("foo", &MyStruct, cache.DefaultExpiration)
74 if x, found := c.Get("foo"); found {
75 foo := x.(*MyStruct)
76 // ...
77 }
78}
79```
80
81### Reference
82
83`godoc` or [http://godoc.org/github.com/patrickmn/go-cache](http://godoc.org/github.com/patrickmn/go-cache)
View as plain text