#go-cache is a memory-based, high-speed caching tool that stores k-v format. It is suitable for applications running on a single machine, can store values of any data type, and can be safely used by multiple goroutines. (Recommended learning: go)
Although go-cache is not intended to be used as a persistent data store, the entire cache data can be saved to a file (or any io.Reader/Writer ), and can quickly load the specified data source from it and quickly restore the state.
Demo
package main import ( "log" "time" "github.com/patrickmn/go-cache" ) func main(){ c := cache.New(30*time.Second, 10*time.Second) c.Set("Title", "Spring Festival", cache.DefaultExpiration) value, found := c.Get("Title") if found { log.Println("found:", value) } else { log.Println("not found") } time.Sleep(60*time.Second) log.Println("sleep 60s...") value, found = c.Get("Title") if found { log.Println("found:", value) } else { log.Println("not found") } }
output
2019/02/05 17:49:32 found: Spring Festival 2019/02/05 17:50:32 sleep 60s… 2019/02/05 17:50:32 not found
First, create a new cache with the key expiration time of 30s. And clear expired keys in the cache every 10 seconds.
Regular clearing of expired keys in the cache is achieved through a resident goroutine.
Next, set a key/value and its expiration time. The expiration time uses the default expiration time, which is 30s.
Get this key, you can see that this key exists in the cache at this time.
Sleep for 60s to expire the key just set.
Get this key again. At this time, the key has expired, been cleared, and is no longer in the cache
The above is the detailed content of Is golang-cache global?. For more information, please follow other related articles on the PHP Chinese website!