mindoc/cache/cache.go

95 lines
1.6 KiB
Go
Raw Normal View History

2018-02-27 17:20:42 +08:00
package cache
import (
"bytes"
"context"
"encoding/gob"
"errors"
"time"
2018-02-27 17:20:42 +08:00
"github.com/beego/beego/v2/client/cache"
"github.com/beego/beego/v2/core/logs"
)
2018-02-27 17:20:42 +08:00
var bm cache.Cache
var nilctx = context.TODO()
func Get(key string, e interface{}) error {
2018-02-27 17:20:42 +08:00
val, err := bm.Get(nilctx, key)
if err != nil {
return errors.New("get cache error:" + err.Error())
}
if val == nil {
return errors.New("cache does not exist")
}
if b, ok := val.([]byte); ok {
buf := bytes.NewBuffer(b)
decoder := gob.NewDecoder(buf)
err := decoder.Decode(e)
if err != nil {
logs.Error("反序列化对象失败 ->", err)
}
return err
} else if s, ok := val.(string); ok && s != "" {
buf := bytes.NewBufferString(s)
decoder := gob.NewDecoder(buf)
err := decoder.Decode(e)
if err != nil {
logs.Error("反序列化对象失败 ->", err)
}
return err
}
return errors.New("value is not []byte or string")
2018-02-27 17:20:42 +08:00
}
func Put(key string, val interface{}, timeout time.Duration) error {
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
err := encoder.Encode(val)
if err != nil {
logs.Error("序列化对象失败 ->", err)
return err
}
return bm.Put(nilctx, key, buf.String(), timeout)
2018-02-27 17:20:42 +08:00
}
2018-02-27 17:20:42 +08:00
func Delete(key string) error {
return bm.Delete(nilctx, key)
2018-02-27 17:20:42 +08:00
}
func Incr(key string) error {
return bm.Incr(nilctx, key)
2018-02-27 17:20:42 +08:00
}
func Decr(key string) error {
return bm.Decr(nilctx, key)
2018-02-27 17:20:42 +08:00
}
func IsExist(key string) (bool, error) {
return bm.IsExist(nilctx, key)
2018-02-27 17:20:42 +08:00
}
func ClearAll() error {
return bm.ClearAll(nilctx)
2018-02-27 17:20:42 +08:00
}
func StartAndGC(config string) error {
return bm.StartAndGC(config)
}
//Init will initialize cache
func Init(c cache.Cache) {
2018-02-27 17:20:42 +08:00
bm = c
}