cache.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package cache
  2. import (
  3. "github.com/astaxie/beego/cache"
  4. "time"
  5. "encoding/gob"
  6. "bytes"
  7. "errors"
  8. "github.com/astaxie/beego"
  9. )
  10. var bm cache.Cache
  11. func Get(key string,e interface{}) error {
  12. val := bm.Get(key)
  13. if val == nil {
  14. return errors.New("cache does not exist")
  15. }
  16. if b,ok := val.([]byte); ok {
  17. buf := bytes.NewBuffer(b)
  18. decoder := gob.NewDecoder(buf)
  19. err := decoder.Decode(e)
  20. if err != nil {
  21. beego.Error("反序列化对象失败 ->", err)
  22. }
  23. return err
  24. }else if s,ok := val.(string); ok && s != "" {
  25. buf := bytes.NewBufferString(s)
  26. decoder := gob.NewDecoder(buf)
  27. err := decoder.Decode(e)
  28. if err != nil {
  29. beego.Error("反序列化对象失败 ->", err)
  30. }
  31. return err
  32. }
  33. return errors.New("value is not []byte or string")
  34. }
  35. func GetMulti(keys []string) []interface{} {
  36. return bm.GetMulti(keys)
  37. }
  38. func Put(key string, val interface{}, timeout time.Duration) error {
  39. var buf bytes.Buffer
  40. encoder := gob.NewEncoder(&buf)
  41. err := encoder.Encode(val)
  42. if err != nil {
  43. beego.Error("序列化对象失败 ->",err)
  44. return err
  45. }
  46. return bm.Put(key, buf.String(), timeout)
  47. }
  48. func Delete(key string) error {
  49. return bm.Delete(key)
  50. }
  51. func Incr(key string) error {
  52. return bm.Incr(key)
  53. }
  54. func Decr(key string) error {
  55. return bm.Decr(key)
  56. }
  57. func IsExist(key string) bool {
  58. return bm.IsExist(key)
  59. }
  60. func ClearAll() error{
  61. return bm.ClearAll()
  62. }
  63. func StartAndGC(config string) error {
  64. return bm.StartAndGC(config)
  65. }
  66. //初始化缓存
  67. func Init(c cache.Cache) {
  68. bm = c
  69. }