|
1 | | -# go-cache |
| 1 | +# Usage |
| 2 | + |
| 3 | +## What |
| 4 | + |
| 5 | +This repo is a wrapper with [go-cache](https://github.com/patrickmn/go-cache). We use `gocache.GetOrSet` to set or get |
| 6 | +cache safely. It means that when multiple threads/go-routing call `gocache.GetOrSet`, the cache will be set only once. |
| 7 | +Usually it means we just call database to retrieve data ONLY one time. |
| 8 | + |
| 9 | +#### Install |
| 10 | + |
| 11 | +``` |
| 12 | +go get -u |
| 13 | +``` |
| 14 | + |
| 15 | +#### STEP 1: Register all your cache keys |
| 16 | + |
| 17 | +```go |
| 18 | +package example |
| 19 | + |
| 20 | +import gocache "go-cache/core" |
| 21 | + |
| 22 | +const ( |
| 23 | + KeyOrders = "KEY_ORDERS" |
| 24 | + KeyUsers = "KEY_USERS" |
| 25 | + KeyBooks = "KEY_BOOKS" |
| 26 | + KeyModules = "KEY_MODULES" |
| 27 | + KeyConfig = "KEY_CONFIG" |
| 28 | +) |
| 29 | + |
| 30 | +func RegisterAllCacheKeys() { |
| 31 | + registry := gocache.GetRegistryInstance() |
| 32 | + registry.Register(&gocache.CacheKey{Key: KeyOrders, Expire: gocache.OneDay}) |
| 33 | + registry.Register(&gocache.CacheKey{Key: KeyUsers, Expire: gocache.OneMinute}) |
| 34 | + registry.Register(&gocache.CacheKey{Key: KeyBooks, Expire: gocache.OneHour}) |
| 35 | + registry.Register(&gocache.CacheKey{Key: KeyModules, Expire: gocache.FiveMinutes}) |
| 36 | + registry.Register(&gocache.CacheKey{Key: KeyConfig, Expire: gocache.OneMinute}) |
| 37 | +} |
| 38 | + |
| 39 | +``` |
| 40 | + |
| 41 | +#### STEP 2: Use `gocache.GetOrSet` to get or set cache thread safely. |
| 42 | + |
| 43 | +```go |
| 44 | +package example |
| 45 | + |
| 46 | +import ( |
| 47 | + gocache "go-cache/core" |
| 48 | + |
| 49 | + log "github.com/sirupsen/logrus" |
| 50 | +) |
| 51 | + |
| 52 | +type Book struct { |
| 53 | + name string |
| 54 | +} |
| 55 | + |
| 56 | +func StartApp() { |
| 57 | + RegisterAllCacheKeys() |
| 58 | + books, ok := gocache.GetOrSet(KeyBooks, func(cache *gocache.CacheKey) (interface{}, error) { |
| 59 | + // you also can call database to retrieve cache here. |
| 60 | + return []Book{ |
| 61 | + {name: "i love coding"}, |
| 62 | + {name: "coding is great"}, |
| 63 | + }, nil |
| 64 | + }) |
| 65 | + |
| 66 | + if ok { |
| 67 | + log.Info("Got books and also set cache.") |
| 68 | + log.Info(books) |
| 69 | + } else { |
| 70 | + log.Info("No books found in cache also in database maybe") |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +example refer to `./example` |
0 commit comments