name: Cache Module

sort: 2

Cache Module

Beego’s cache module is used for caching data, inspired by database/sql. It supports four cache providers: file, memcache, memory and redis. You can install it by:

  1. go get github.com/astaxie/beego/cache

If you use the memcache or redis provider, you should first install:

  1. go get -u github.com/astaxie/beego/cache/memcache

and then import:

  1. import _ "github.com/astaxie/beego/cache/memcache"

Basic Usage

First step is importing the package:

  1. import (
  2. "github.com/astaxie/beego/cache"
  3. )

Then initialize a global variable object:

  1. bm, err := cache.NewCache("memory", `{"interval":60}`)

Then we can use bm to modify the cache:

  1. bm.Put("astaxie", 1, 10*time.Second)
  2. bm.Get("astaxie")
  3. bm.IsExist("astaxie")
  4. bm.Delete("astaxie")

Provider Settings

Here is how to configure the four providers:

  • memory

    interval stands for GC time, which means the cache will be cleared every 60s:

    1. {"interval":60}
  • file

    1. {"CachePath":"./cache","FileSuffix":".cache","DirectoryLevel":2,"EmbedExpiry":120}
  • redis

    redis is using redigo

    1. {"conn":":6039"}
  • memcache

    memcache is using vitess

    1. {"conn":"127.0.0.1:11211"}

Creating your own provider

The cache module uses the Cache interface, so you can create your own cache provider by implementing this interface and registering it.

  1. type Cache interface {
  2. Get(key string) interface{}
  3. Put(key string, val interface{}, timeout time.Duration) error
  4. Delete(key string) error
  5. Incr(key string) error
  6. Decr(key string) error
  7. IsExist(key string) bool
  8. ClearAll() error
  9. StartAndGC(config string) error
  10. }

Register your provider:

  1. func init() {
  2. cache.Register("myowncache", NewOwnCache())
  3. }