Improve this page on GitHub

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:

go get

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

go get -u

and then import:

import _ ""

Basic Usage

First step is importing the package:

import (

Then initialize a global variable object:

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

Then we can use bm to modify the cache:

bm.Put("astaxie", 1, 10*time.Second)

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:

  • file

  • redis

    redis uses redigo

    • key: the Redis collection name
    • conn: Redis connection info
    • dbNum: Select the DB having the specified zero-based numeric index.
    • password: the password for connecting password-protected Redis server
  • memcache

    memcache uses vitess


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.

type Cache interface {
    Get(key string) interface{}
    GetMulti(keys []string) []interface{}
    Put(key string, val interface{}, timeout time.Duration) error
    Delete(key string) error
    Incr(key string) error
    Decr(key string) error
    IsExist(key string) bool
    ClearAll() error
    StartAndGC(config string) error

Register your provider:

func init() {
    cache.Register("myowncache", NewOwnCache())
comments powered by Disqus