1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- local skynet = require "skynet"
- local snax = require "snax"
- local Redis = {
- pool = nil
- }
- local function hash_key(key)
- local value = 0
- for i = 1, #key do
- value = value + string.byte(key, i)
- end
- return value
- end
- local function get_uid(key)
- local pos = string.find(key, "uid:")
- if pos then
- return tonumber(string.sub(key, pos + 4, #key))
- end
- return false
- end
- -- 玩家数据分片
- function Redis:get_db(key)
- local uid = get_uid(key)
- if not uid then
- uid = hash_key(key)
- end
- local dbs = self.pool[uid % #self.pool + 1]
- return dbs[math.random(1, #dbs)]
- end
- function Redis:get_redis_pool()
- if self.pool and #self.pool > 0 then
- return
- end
- local redis_sup = snax.queryservice("srvRedisMgr")
- local pool = redis_sup.req.acquire(self.name)
- self.pool = {}
- for k, v in pairs(pool) do
- local dbs = {}
- for c, handle in pairs(v) do
- dbs[c] = handle
- end
- self.pool[k] = dbs
- end
- end
- function Redis:new(name)
- local o = {}
- setmetatable(o, self)
- self.__index = self
- o.name = name
- o.pool = {}
- return o
- end
- setmetatable(
- Redis,
- {
- __index = function(t, k)
- local cmd = string.lower(k)
- local function f(self, ...)
- self:get_redis_pool()
- local db = self:get_db(select(1, ...))
- return skynet.call(db, "lua", "query", cmd, ...)
- end
- t[k] = f
- return f
- end
- }
- )
- local root = {}
- local mapRedis = {}
- function root.get_redis(name)
- local rd = mapRedis[name]
- if rd then
- return rd
- end
- rd = Redis:new(name)
- mapRedis[name] = rd
- return rd
- end
- return root
|