common.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "go-common/app/service/bbq/topic/internal/model"
  6. "go-common/library/cache/redis"
  7. "go-common/library/ecode"
  8. "go-common/library/log"
  9. "go-common/library/xstr"
  10. )
  11. /*各种情况下,是否需要查询db,前三列表示情景条件
  12. NEXT offset rank 是否需要db操作
  13. 1 1
  14. 0 1 0 0
  15. 0 n>1 0 1
  16. 0 0 n>0 0
  17. */
  18. func parseCursor(ctx context.Context, cursorPrev, cursorNext string) (cursor model.CursorValue, directionNext bool, err error) {
  19. // 判断是向前还是向后查询
  20. directionNext = true
  21. cursorStr := cursorNext
  22. if len(cursorNext) == 0 && len(cursorPrev) > 0 {
  23. directionNext = false
  24. cursorStr = cursorPrev
  25. }
  26. // 解析cursor中的cursor_id
  27. if len(cursorStr) != 0 {
  28. var cursorData = []byte(cursorStr)
  29. err = json.Unmarshal(cursorData, &cursor)
  30. if err != nil {
  31. err = ecode.ReqParamErr
  32. return
  33. }
  34. }
  35. // 最后做一次校验,保证cursor的值是对的
  36. if (cursor.StickRank > 0 && cursor.Offset > 0) || (!directionNext && cursor.Offset == 0 && cursor.StickRank == 0) {
  37. err = ecode.TopicReqParamErr
  38. log.Errorw(ctx, "log", "cursor value error", "prev", cursorPrev, "next", cursorNext)
  39. return
  40. }
  41. return
  42. }
  43. func (d *Dao) getRedisList(ctx context.Context, key string) (list []int64, err error) {
  44. conn := d.redis.Get(ctx)
  45. defer conn.Close()
  46. str, err := redis.String(conn.Do("GET", key))
  47. if err == redis.ErrNil {
  48. err = nil
  49. return
  50. }
  51. if err != nil {
  52. log.Errorw(ctx, "log", "get redis list fail", "key", key)
  53. return
  54. }
  55. list, err = xstr.SplitInts(str)
  56. if err != nil {
  57. log.Errorw(ctx, "log", "split list_str fail", "key", key, "str", str)
  58. return
  59. }
  60. return
  61. }
  62. func (d *Dao) setRedisList(ctx context.Context, key string, list []int64) (err error) {
  63. conn := d.redis.Get(ctx)
  64. defer conn.Close()
  65. if _, err = conn.Do("SET", key, xstr.JoinInts(list)); err != nil {
  66. log.Errorw(ctx, "log", "set redis list fail", "key", key, "list", list)
  67. return
  68. }
  69. return
  70. }