snowflake.lua 773 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. local skynet = require "skynet"
  2. require "skynet.manager"
  3. local c = require "snowflake.core"
  4. local skynet_retpack = skynet.retpack
  5. local prefix = nil
  6. local MAX_WORKID_VAL = 1024
  7. local CMD = {}
  8. function CMD.start()
  9. local work_id = assert(option.sid)
  10. if work_id < 1 or work_id > 65535 then
  11. assert(false, "Work id is in range of 1 - 65535.")
  12. end
  13. prefix = string.format("%02d-", work_id>>10)
  14. work_id = work_id % MAX_WORKID_VAL
  15. c.init(work_id)
  16. end
  17. function CMD.prefix()
  18. return prefix
  19. end
  20. skynet.init(function()
  21. skynet.register(".snowflake")
  22. end)
  23. skynet.start(function()
  24. skynet.dispatch("lua", function(session, _, cmd, ...)
  25. local f = assert(CMD[cmd])
  26. if session == 0 then
  27. f(...)
  28. else
  29. skynet_retpack(f(...))
  30. end
  31. end)
  32. end)