service.lua 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. local skynet = require "skynet"
  2. local cluster = require "skynet.cluster"
  3. local M = {
  4. --类型和id
  5. name = "",
  6. id = 0,
  7. --回调函数
  8. exit = nil,
  9. init = nil,
  10. --分发方法
  11. resp = {},
  12. }
  13. --[[
  14. function exit_dispatch()
  15. if M.exit then
  16. M.exit()
  17. end
  18. skynet.ret()
  19. skynet.exit()
  20. end
  21. --]]
  22. function traceback(err)
  23. skynet.error(tostring(err))
  24. skynet.error(debug.traceback())
  25. end
  26. local dispatch = function(session, address, cmd, ...)
  27. local fun = M.resp[cmd]
  28. if not fun then
  29. skynet.ret()
  30. return
  31. end
  32. local ret = table.pack(xpcall(fun, traceback, address, ...))
  33. local isok = ret[1]
  34. if not isok then
  35. skynet.ret()
  36. return
  37. end
  38. skynet.retpack(table.unpack(ret,2))
  39. end
  40. function init()
  41. skynet.dispatch("lua", dispatch)
  42. if M.init then
  43. M.init()
  44. end
  45. end
  46. function M.call(node, srv, ...)
  47. local mynode = skynet.getenv("node")
  48. if node == mynode then
  49. return skynet.call(srv, "lua", ...)
  50. else
  51. return cluster.call(node, srv, ...)
  52. end
  53. end
  54. function M.send(node, srv, ...)
  55. local mynode = skynet.getenv("node")
  56. if node == mynode then
  57. return skynet.send(srv, "lua", ...)
  58. else
  59. return cluster.send(node, srv, ...)
  60. end
  61. end
  62. function M.start(name, id, ...)
  63. M.name = name
  64. M.id = tonumber(id)
  65. skynet.start(init)
  66. end
  67. M.resp.exit = function()
  68. if M.exit then
  69. M.exit()
  70. end
  71. skynet.ret()
  72. skynet.exit()
  73. end
  74. return M