官术网_书友最值得收藏!

  • Machine Learning With Go
  • Daniel Whitenack
  • 135字
  • 2021-07-08 10:37:28

Caching data in memory

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 seconds
c := 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 {
fmt.Printf("key: mykey, value: %s\n", v)
}
主站蜘蛛池模板: 山西省| 文化| 郸城县| 双峰县| 珲春市| 应城市| 陆良县| 湘西| 三河市| 清流县| 临桂县| 商洛市| 彭水| 满洲里市| 慈溪市| 日照市| 湄潭县| 安图县| 历史| 健康| 通渭县| 奉贤区| 金华市| 曲周县| 汉中市| 成都市| 浏阳市| 龙海市| 多伦县| 南陵县| 遵化市| 威信县| 新泰市| 沂南县| 西畴县| 平谷区| 衡阳县| 洛隆县| 永吉县| 永川市| 永济市|