cache.go 1.6 KB

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