rpcRedis.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. local skynet = require "skynet"
  2. local snax = require "snax"
  3. local Redis = {
  4. pool = nil
  5. }
  6. local function hash_key(key)
  7. local value = 0
  8. for i = 1, #key do
  9. value = value + string.byte(key, i)
  10. end
  11. return value
  12. end
  13. local function get_uid(key)
  14. local pos = string.find(key, "uid:")
  15. if pos then
  16. return tonumber(string.sub(key, pos + 4, #key))
  17. end
  18. return false
  19. end
  20. -- 玩家数据分片
  21. function Redis:get_db(key)
  22. local uid = get_uid(key)
  23. if not uid then
  24. uid = hash_key(key)
  25. end
  26. local dbs = self.pool[uid % #self.pool + 1]
  27. return dbs[math.random(1, #dbs)]
  28. end
  29. function Redis:get_redis_pool()
  30. if self.pool and #self.pool > 0 then
  31. return
  32. end
  33. local redis_sup = snax.queryservice("srvRedisMgr")
  34. local pool = redis_sup.req.acquire(self.name)
  35. self.pool = {}
  36. for k, v in pairs(pool) do
  37. local dbs = {}
  38. for c, handle in pairs(v) do
  39. dbs[c] = handle
  40. end
  41. self.pool[k] = dbs
  42. end
  43. end
  44. function Redis:new(name)
  45. local o = {}
  46. setmetatable(o, self)
  47. self.__index = self
  48. o.name = name
  49. o.pool = {}
  50. return o
  51. end
  52. setmetatable(
  53. Redis,
  54. {
  55. __index = function(t, k)
  56. local cmd = string.lower(k)
  57. local function f(self, ...)
  58. self:get_redis_pool()
  59. local db = self:get_db(select(1, ...))
  60. return skynet.call(db, "lua", "query", cmd, ...)
  61. end
  62. t[k] = f
  63. return f
  64. end
  65. }
  66. )
  67. local root = {}
  68. local mapRedis = {}
  69. function root.get_redis(name)
  70. local rd = mapRedis[name]
  71. if rd then
  72. return rd
  73. end
  74. rd = Redis:new(name)
  75. mapRedis[name] = rd
  76. return rd
  77. end
  78. return root