Skip to content

Instantly share code, notes, and snippets.

@hanxi

hanxi/calculate.lua

Created May 24, 2019
Embed
What would you like to do?
Skynet 动态控制无状态服务的数量
-- calculate.lua
local skynet = require "skynet"
local CMD = {}
function CMD.calculate(a, b)
return a^b
end
function CMD.exit()
skynet.error("slave exit.")
skynet.ret()
skynet.exit()
-- exit() 之后的代码是不会执行的
end
skynet.start(function()
skynet.dispatch("lua", function(_,_,cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(...)))
else
error(string.format("Unknown cmd:%s", tostring(cmd)))
end
end)
end)
-- calculate_mng.lua
local skynet = require "skynet"
require "skynet.manager" -- import skynet.register
-- 存放无状态服务
local SLAVE_SERVICE_NAME = "calculate"
local MASTER_SERVICE_NAME = "calculate_mng"
local slave = {}
local balance = 1
local CMD = {}
-- 找一个 slave 帮忙做点复杂的计算
function CMD.calculate(a, b)
local s = slave[balance]
balance = balance + 1
if balance > #slave then
balance = 1
end
return skynet.call(s, "lua", "calculate", a, b)
end
-- 返回每个 slave 的信息
function CMD.info()
local msg = string.format("total slave count:%d", #slave)
return msg
end
-- 重置 slave 的数量(收缩)
-- skynet.call("calculate_mng", "lua", "set_slave_count", 3)
function CMD.set_slave_count(cnt)
local now_cnt = #slave
if now_cnt == cnt then
skynet.error(string.format("slave count is:%d", now_cnt))
return
end
balance = 1
if now_cnt > cnt then
local kill_cnt = now_cnt - cnt
for _=1,kill_cnt do
local s = slave[#slave]
skynet.call(s, "lua", "exit")
table.remove(slave)
end
skynet.error(string.format("slave old_cnt:%d, new_cnt:%d", now_cnt, #slave))
return
end
if now_cnt < cnt then
local add_cnt = cnt - now_cnt
for _=1,add_cnt do
table.insert(slave, skynet.newservice(SLAVE_SERVICE_NAME))
end
skynet.error(string.format("slave old_cnt:%d, new_cnt:%d", now_cnt, #slave))
return
end
end
skynet.start(function()
skynet.register(MASTER_SERVICE_NAME)
local instance = 8 -- 默认值可以读取配置
skynet.dispatch("lua", function(_,_,cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(...)))
else
error(string.format("Unknown cmd:%s", tostring(cmd)))
end
end)
for _=1,instance do
table.insert(slave, skynet.newservice(SLAVE_SERVICE_NAME))
end
end)
-- test.lua
skynet.start(function()
skynet.uniqueservice("calculate_mng")
skynet.exit()
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment