robot_pool.lua
983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
--[[
	deque 为了减少锁竞争,尽量保证 a服务 push;b服务 pop
]]
local skynet = require "skynet"
local deque = require "deque"
local CMD = {}
local factory
local PRE_FEED_COUNT = 5
local dead = 0
-- agent死亡,通知poold补充,当累计到5个agent时,马上生成5个agent放入poold中
-- 当然这里也可以写得更复杂,参考redis落地规则
function CMD.feed()
	dead = dead + 1
	if dead == PRE_FEED_COUNT then
		dead = 0
		for i=1, PRE_FEED_COUNT do
			factory:push(skynet.newservice("robot"))
		end
	end
end
-- 系统启动,生成count个agent放入双端队列中
function CMD.start(count)
	factory, addr = deque.new(count)
	for i = 1, count do
		factory:push(skynet.newservice("robot"))
	end
	return addr
end
local function __init__()
	skynet.dispatch("lua", function (_, _, command, ...)
		local f = CMD[command]
		if command == "start" then
			skynet.ret(skynet.pack(f(...)))
			return
		end
		f(...)
	end)
end
skynet.start(__init__)