cache.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 Put(key string, val interface{}, timeout time.Duration) error {
  36. var buf bytes.Buffer
  37. encoder := gob.NewEncoder(&buf)
  38. err := encoder.Encode(val)
  39. if err != nil {
  40. beego.Error("序列化对象失败 ->", err)
  41. return err
  42. }
  43. return bm.Put(key, buf.String(), timeout)
  44. }
  45. func Delete(key string) error {
  46. return bm.Delete(key)
  47. }
  48. func Incr(key string) error {
  49. return bm.Incr(key)
  50. }
  51. func Decr(key string) error {
  52. return bm.Decr(key)
  53. }
  54. func IsExist(key string) bool {
  55. return bm.IsExist(key)
  56. }
  57. func ClearAll() error {
  58. return bm.ClearAll()
  59. }
  60. func StartAndGC(config string) error {
  61. return bm.StartAndGC(config)
  62. }
  63. //初始化缓存
  64. func Init(c cache.Cache) {
  65. bm = c
  66. }