gtoken_cache.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package gtoken
  2. import (
  3. "github.com/gogf/gf/encoding/gjson"
  4. "github.com/gogf/gf/frame/g"
  5. "github.com/gogf/gf/os/gcache"
  6. "github.com/gogf/gf/os/glog"
  7. "github.com/gogf/gf/util/gconv"
  8. "time"
  9. )
  10. // setCache 设置缓存
  11. func (m *GfToken) setCache(cacheKey string, userCache g.Map) Resp {
  12. switch m.CacheMode {
  13. case CacheModeCache:
  14. gcache.Set(cacheKey, userCache, gconv.Duration(m.Timeout)*time.Millisecond)
  15. case CacheModeRedis:
  16. cacheValueJson, err1 := gjson.Encode(userCache)
  17. if err1 != nil {
  18. glog.Error("[GToken]cache json encode error", err1)
  19. return Error("cache json encode error")
  20. }
  21. _, err := g.Redis().Do("SETEX", cacheKey, m.Timeout, cacheValueJson)
  22. if err != nil {
  23. glog.Error("[GToken]cache set error", err)
  24. return Error("cache set error")
  25. }
  26. default:
  27. return Error("cache model error")
  28. }
  29. return Succ(userCache)
  30. }
  31. // getCache 获取缓存
  32. func (m *GfToken) getCache(cacheKey string) Resp {
  33. var userCache g.Map
  34. switch m.CacheMode {
  35. case CacheModeCache:
  36. userCacheValue, _ := gcache.Get(cacheKey)
  37. if userCacheValue == nil {
  38. return Unauthorized("login timeout or not login", "")
  39. }
  40. userCache = gconv.Map(userCacheValue)
  41. case CacheModeRedis:
  42. userCacheJson, err := g.Redis().Do("GET", cacheKey)
  43. if err != nil {
  44. glog.Error("[GToken]cache get error", err)
  45. return Error("cache get error")
  46. }
  47. if userCacheJson == nil {
  48. return Unauthorized("login timeout or not login", "")
  49. }
  50. err = gjson.DecodeTo(userCacheJson, &userCache)
  51. if err != nil {
  52. glog.Error("[GToken]cache get json error", err)
  53. return Error("cache get json error")
  54. }
  55. default:
  56. return Error("cache model error")
  57. }
  58. return Succ(userCache)
  59. }
  60. // removeCache 删除缓存
  61. func (m *GfToken) removeCache(cacheKey string) Resp {
  62. switch m.CacheMode {
  63. case CacheModeCache:
  64. gcache.Remove(cacheKey)
  65. case CacheModeRedis:
  66. var err error
  67. _, err = g.Redis().Do("DEL", cacheKey)
  68. if err != nil {
  69. glog.Error("[GToken]cache remove error", err)
  70. return Error("cache remove error")
  71. }
  72. default:
  73. return Error("cache model error")
  74. }
  75. return Succ("")
  76. }