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. github.com/beego/beego/v2/client/cache

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

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

and then import:

  1. import _ "github.com/beego/beego/v2/client/cache/memcache"

Basic Usage

First step is importing the package:

  1. import (
  2. "github.com/beego/beego/v2/client/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 uses redigo

    1. {"key":"collectionName","conn":":6039","dbNum":"0","password":"thePassWord"}
    • 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

    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 a cached value by key.
  3. Get(ctx context.Context, key string) (interface{}, error)
  4. // GetMulti is a batch version of Get.
  5. GetMulti(ctx context.Context, keys []string) ([]interface{}, error)
  6. // Set a cached value with key and expire time.
  7. Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error
  8. // Delete cached value by key.
  9. Delete(ctx context.Context, key string) error
  10. // Increment a cached int value by key, as a counter.
  11. Incr(ctx context.Context, key string) error
  12. // Decrement a cached int value by key, as a counter.
  13. Decr(ctx context.Context, key string) error
  14. // Check if a cached value exists or not.
  15. IsExist(ctx context.Context, key string) (bool, error)
  16. // Clear all cache.
  17. ClearAll(ctx context.Context) error
  18. // Start gc routine based on config string settings.
  19. StartAndGC(config string) error
  20. }

Register your provider:

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