or保持50并发请求第三方接口

当时有一个需求,发送1w个请求,保持50个并发,用or实现代码如下:

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
_M.parallel = function(self)
local coNum = 50
local reqList = {}
for i=1,10000,1 do
table.insert(reqList, 'http://127.0.0.1:6565/respParallel')
end

local count = 0

local reqFunc = function(i)

-- ngx.log(ngx.ERR, "============", count, #reqList, "=======")

while count <= #reqList do
ngx.sleep(0)
count = count + 1
local request_url = reqList[count]
if not request_url then
break
end

-- 发送http请求获取od和map的对应关系
local httpc = http.new()
httpc:set_timeout(60000)
-- 拼接请求参数
local opt = {
method = "GET",
}

local res, err = httpc:request_uri(request_url, opt)
if err then
--ngx.log(ngx.ERR, string.format("thread [%s] request error count [%s] error, %s", i, count, err))
else
--ngx.log(ngx.ERR, string.format("thread [%s] request complete count[%s], body [%s]", i, count, res.body))
end
end

local msg = "thread [%s] complete"
--ngx.log(ngx.ERR, string.format(msg, i))

return msg
end


local threads = {}
for i=0,coNum,1 do
table.insert(threads, (ngx.thread.spawn(reqFunc, i)))
end


for i = 1, #threads do
local result = ngx.thread.wait(threads[i])
ngx.say(result)
end

local result, err = ngx.shared.cachDict:get("pcount")
ngx.say(string.format("=== total: %s ===", result))

return ""

end