Thursday 16 May 2019

Introduction to go-cache


Setup
go get github.com/patrickmn/go-cache

Hello World Application
go-cache is an in-memory <key,value> store. You can create a cache, where key os of type string and value is of any type.

How to create a cache?
You can create a cache using 'cache.New' function.

For example, below statement creates a cache, where expiry time is 5 minutes and remove expired items for every 10 minutes
myCache := cache.New(5*time.Minute, 10*time.Minute)

How to insert <key, value> into a cache?
Using Set method, you can insert elements into cache.

For example, below statement insert 'key' as 'defaultRegion' and 'value' as 'India'. As you see I am informing to use cache default expiration time (5 minutes here) for this key.
myCache.Set("defaultRegion", "India", cache.DefaultExpiration)

How to set no expiration time for the cache?
Using 'cache.NoExpiration' property, you can make a key never expires
myCache.Set("discount", 12, cache.NoExpiration)

How to get a value from cache?
Using Get method, you can get a value from cache.

defaultRegion, found := myCache.Get("defaultRegion")
if found {
         fmt.Println(defaultRegion)
}

App.go

package main

import (
 "fmt"
 "github.com/patrickmn/go-cache"
 "time"
)

func main() {
 //Expiry time is 5 minutes and remove expired items for every 10 minutes
 myCache := cache.New(5*time.Minute, 10*time.Minute)

 //Set the key "foo" with value "bar" and set default expiration time
 myCache.Set("defaultRegion", "India", cache.DefaultExpiration)

 //Set the key "discount" with value 12
 myCache.Set("discount", 12, cache.NoExpiration)

 defaultRegion, found := myCache.Get("defaultRegion")
 if found {
  fmt.Println(defaultRegion)
 }

 discount, found := myCache.Get("discount")
 if found {
  fmt.Println(discount)
 }

}

Output
India
12

Reference
https://github.com/patrickmn/go-cache


No comments:

Post a Comment