2018-02-27 17:20:42 +08:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
2018-07-25 14:46:56 +08:00
|
|
|
"bytes"
|
2021-03-30 14:24:14 +08:00
|
|
|
"encoding/gob"
|
2018-07-25 14:46:56 +08:00
|
|
|
"errors"
|
2021-03-30 14:24:14 +08:00
|
|
|
"github.com/astaxie/beego/cache"
|
|
|
|
"github.com/astaxie/beego/logs"
|
|
|
|
"time"
|
2018-02-27 17:20:42 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var bm cache.Cache
|
|
|
|
|
2018-08-13 15:04:52 +08:00
|
|
|
func Get(key string, e interface{}) error {
|
2018-02-27 17:20:42 +08:00
|
|
|
|
2018-07-25 14:46:56 +08:00
|
|
|
val := bm.Get(key)
|
|
|
|
|
|
|
|
if val == nil {
|
|
|
|
return errors.New("cache does not exist")
|
|
|
|
}
|
2018-08-13 15:04:52 +08:00
|
|
|
if b, ok := val.([]byte); ok {
|
2018-07-25 14:46:56 +08:00
|
|
|
buf := bytes.NewBuffer(b)
|
|
|
|
|
|
|
|
decoder := gob.NewDecoder(buf)
|
|
|
|
|
|
|
|
err := decoder.Decode(e)
|
|
|
|
|
|
|
|
if err != nil {
|
2021-03-30 14:24:14 +08:00
|
|
|
logs.Error("反序列化对象失败 ->", err)
|
2018-07-25 14:46:56 +08:00
|
|
|
}
|
|
|
|
return err
|
2018-08-13 15:04:52 +08:00
|
|
|
} else if s, ok := val.(string); ok && s != "" {
|
2018-07-25 14:56:46 +08:00
|
|
|
|
|
|
|
buf := bytes.NewBufferString(s)
|
|
|
|
|
|
|
|
decoder := gob.NewDecoder(buf)
|
|
|
|
|
|
|
|
err := decoder.Decode(e)
|
|
|
|
|
|
|
|
if err != nil {
|
2021-03-30 14:24:14 +08:00
|
|
|
logs.Error("反序列化对象失败 ->", err)
|
2018-08-13 15:04:52 +08:00
|
|
|
}
|
2018-07-25 14:56:46 +08:00
|
|
|
return err
|
2018-07-25 14:46:56 +08:00
|
|
|
}
|
2018-07-25 14:56:46 +08:00
|
|
|
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 {
|
|
|
|
|
2018-07-25 14:46:56 +08:00
|
|
|
var buf bytes.Buffer
|
|
|
|
|
|
|
|
encoder := gob.NewEncoder(&buf)
|
|
|
|
|
|
|
|
err := encoder.Encode(val)
|
|
|
|
if err != nil {
|
2021-03-30 14:24:14 +08:00
|
|
|
logs.Error("序列化对象失败 ->", err)
|
2018-07-25 14:46:56 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bm.Put(key, buf.String(), timeout)
|
2018-02-27 17:20:42 +08:00
|
|
|
}
|
2018-07-25 14:46:56 +08:00
|
|
|
|
2018-02-27 17:20:42 +08:00
|
|
|
func Delete(key string) error {
|
|
|
|
return bm.Delete(key)
|
|
|
|
}
|
|
|
|
func Incr(key string) error {
|
|
|
|
return bm.Incr(key)
|
|
|
|
}
|
|
|
|
func Decr(key string) error {
|
|
|
|
return bm.Decr(key)
|
|
|
|
}
|
|
|
|
func IsExist(key string) bool {
|
|
|
|
return bm.IsExist(key)
|
|
|
|
}
|
2018-08-13 15:04:52 +08:00
|
|
|
func ClearAll() error {
|
2018-02-27 17:20:42 +08:00
|
|
|
return bm.ClearAll()
|
|
|
|
}
|
|
|
|
|
|
|
|
func StartAndGC(config string) error {
|
|
|
|
return bm.StartAndGC(config)
|
|
|
|
}
|
2018-08-13 15:04:52 +08:00
|
|
|
|
2018-02-27 17:20:42 +08:00
|
|
|
//初始化缓存
|
2018-08-13 15:04:52 +08:00
|
|
|
func Init(c cache.Cache) {
|
2018-02-27 17:20:42 +08:00
|
|
|
bm = c
|
2018-08-13 15:04:52 +08:00
|
|
|
}
|