cache.go 1.3 KB

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