September 2017
Beginner to intermediate
304 pages
7h 2m
English
To cache a series of values in memory, we will use github.com/patrickmn/go-cache. With this package, we can create an in-memory cache of keys and corresponding values. We can even specify things, such as the time to live, in the cache for specific key-value pairs.
To create a new in-memory cache and set a key-value pair in the cache, we do the following:
// Create a cache with a default expiration time of 5 minutes, and which// purges expired items every 30 secondsc := cache.New(5*time.Minute, 30*time.Second)// Put a key and value into the cache.c.Set("mykey", "myvalue", cache.DefaultExpiration)
To then retrieve the value for mykey out of the cache, we just need to use the Get method:
v, found := c.Get("mykey")if found ...Read now
Unlock full access