rpcMysql.lua 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. --[[
  2. Descripttion:
  3. version:
  4. Author: Neo,Huang
  5. Date: 2022-07-04 15:45:50
  6. LastEditors: Neo,Huang
  7. LastEditTime: 2022-07-04 15:46:07
  8. --]]
  9. local skynet = require "skynet"
  10. local snax = require "snax"
  11. local Mysql = {
  12. mysql_sup = nil,
  13. pool = nil
  14. }
  15. function Mysql:query(...)
  16. if not self.mysql_sup then
  17. self.mysql_sup = snax.queryservice("srvMysqlMgr")
  18. end
  19. if not self.pool or #self.pool == 0 then
  20. self.pool = {} -- get mysql pool
  21. local pool = self.mysql_sup.req.acquire(self.name)
  22. for k, v in ipairs(pool) do
  23. self.pool[k] = v
  24. end
  25. end
  26. if #self.pool == 0 then
  27. return
  28. end
  29. local db = self.pool[math.random(1, #self.pool)]
  30. return skynet.call(db, "lua", "query", ...)
  31. end
  32. function Mysql:new(name)
  33. local o = {}
  34. setmetatable(o, self)
  35. self.__index = self
  36. o.name = name
  37. return o
  38. end
  39. local root = {}
  40. local MYSQL = {}
  41. function root.get_mysql(name)
  42. local mysql = MYSQL[name]
  43. if mysql then
  44. return mysql
  45. end
  46. mysql = Mysql:new(name)
  47. MYSQL[name] = mysql
  48. return mysql
  49. end
  50. return root