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

  • 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)
}
主站蜘蛛池模板: 兖州市| 固始县| 安溪县| 措美县| 台湾省| 施秉县| 建德市| 香港| 敦煌市| 法库县| 聂拉木县| 泰顺县| 云阳县| 津南区| 南丰县| 娱乐| 蚌埠市| 江北区| 楚雄市| 灵寿县| 汪清县| 五大连池市| 莱西市| 林周县| 恩施市| 湖南省| 永新县| 柘城县| 衢州市| 莫力| 合作市| 昭通市| 天门市| 大丰市| 高雄市| 西充县| 长垣县| 靖安县| 城固县| 奇台县| 绵阳市|