Implementing caching in Beego
Caching data in a web application is sometimes necessary to avoid requesting the static data from a database or external service again and again. In this recipe, we will learn how we can implement caching in a Beego application.
Beego supports four cache providers: file
, Memcache
, memory
, and Redis
. In this recipe, we will be working with the framework default cache provider, which is a memory
cache provider.
How to do it…
- Install the
github.com/astaxie/beego/cache
package using thego get
command, as follows:
$ go get github.com/astaxie/beego/cache
- Move to
$GOPATH/src/my-first-beego-project/controllers
and createcachecontroller.go
, where we will define theGetFromCache
handler, which will get the value for a key from a cache and write it to an HTTP response, as follows:
package controllers import ( "fmt" "time" "github.com/astaxie/beego" "github.com/astaxie/beego/cache" ) type CacheController struct { beego.Controller } var beegoCache cache.Cache var...