redisBattleUtil.lua 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. --[[
  2. Descripttion:
  3. version:
  4. Author: Neo,Huang
  5. Date: 2022-01-06 16:50:11
  6. LastEditors: Neo,Huang
  7. LastEditTime: 2022-01-25 16:30:38
  8. --]]
  9. local lib_battle_redis = require("lib_battle_redis")
  10. -- redis基础操作
  11. -- 本文件所有处理不会对module对应的数据库进行操作,玩家个人数据请使用 data.module
  12. local root = {}
  13. ----------------------------------------
  14. -- main key
  15. ----------------------------------------
  16. function root.get_int(key)
  17. local val = lib_battle_redis:get(key)
  18. return val and tonumber(val) or 0
  19. end
  20. function root.get_json(key)
  21. local val = lib_battle_redis:get(key)
  22. val = val and cjson_decode(val) or {}
  23. -- 主要针对C++中的NULL
  24. if is_empty(val) then
  25. val = {}
  26. end
  27. return val
  28. end
  29. ----------------------------------------
  30. -- subKey
  31. ----------------------------------------
  32. function root.hset(tb, key, val)
  33. if is_empty(tb) or is_empty(key) then
  34. return
  35. end
  36. if is_nil(val) then
  37. return root.hdel(tb, key)
  38. end
  39. local info = val
  40. if type(val) == "table" then
  41. info = cjson_encode(val)
  42. end
  43. return lib_battle_redis:hset(tb, key, info)
  44. end
  45. function root.hget_int(tb, key)
  46. local val = lib_battle_redis:hget(tb, key)
  47. return val and tonumber(val) or 0
  48. end
  49. function root.hget_json(tb, key)
  50. local val = lib_battle_redis:hget(tb, key)
  51. val = val and cjson_decode(val) or {}
  52. -- 主要针对C++中的NULL
  53. if is_empty(val) then
  54. val = {}
  55. end
  56. return val
  57. end
  58. function root.hmset(key, mapData)
  59. if is_empty(key) or is_empty(mapData) then
  60. return false
  61. end
  62. local res = {}
  63. for k, v in pairs(mapData) do
  64. table.insert(res, k)
  65. table.insert(res, v)
  66. end
  67. return lib_battle_redis:hmset(key, table.unpack(res))
  68. end
  69. -- 获取模块所有数据
  70. function root.hgetall(key)
  71. local data = lib_battle_redis:hgetall(key)
  72. if not is_empty(data) then
  73. local ret = {}
  74. for i = 1, #data, 2 do
  75. ret[data[i]] = data[i + 1]
  76. end
  77. return ret
  78. end
  79. end
  80. function root.do_eval(evalkey, keyCount, ...)
  81. local data = lib_battle_redis:eval(root.evalStr[evalkey], keyCount, ...)
  82. return data
  83. end
  84. -- redis 执行 lua 脚本.
  85. root.evalStr = {
  86. ["aaa"] = [[redis.call('lpush', KEYS[1], ARGV[1]); redis.call('ltrim', KEYS[1], 0, ARGV[2]);]],
  87. ["bbb"] = [["redis.call('zincrby',KEYS[1], ARGV[1], ARGV[2]);
  88. local scores = redis.call('zscore', KEYS[1], ARGV[2]);
  89. local rank = redis.call('zrevrank', KEYS[1], ARGV[2]);
  90. return {rank, scores};]]
  91. }
  92. return root