特性
项目源码
github.com/helloJiu/op…
代码
local http = require("resty/http")
local config = {
max_idle_time = 30000,
pool_size = 1000,
timeout = 5000,
backlog = 1000
}
local _M = {}
function _M.new()
local instance = {
timeout = config.timeout or 5000,
max_idle_time = config.max_idle_time or 60000,
pool_size = config.pool_size or 1000,
backlog = config.backlog or 1000,
}
setmetatable(instance, { __index = _M })
return instance
end
function _M:exec(options, func)
local httpc = http:new()
httpc:set_timeout(self.timeout)
options.pool_size = self.pool_size
options.backlog = self.backlog
options.ssl_verify = false
local ok, err = httpc:connect(options)
if not ok then
ngx.log(ngx.ERR, "http connect, err:", err)
return nil, err
end
local res, err = func(httpc)
if not res then
ngx.log(ngx.ERR, "http request, err:", err)
return nil, err
end
local res_body = ""
if res.status == 200 and res.has_body then
local reader = res.body_reader
local buffer_size = 4096
repeat
local buffer, err = reader(buffer_size)
if err then
ngx.log(ngx.ERR, "reader err", err)
break
end
if buffer then
res_body = res_body .. buffer
end
until not buffer
end
local ok = httpc:set_keepalive(self.max_idle_time, self.pool_size)
if not ok then
httpc:close()
end
return res_body, res, err
end
return _M
实际使用
local http = require("http")
local path = string.format("/cgi-bin/qrcode/create?access_token=%s", "accessToken")
local httpi = http.new()
local options = {
scheme = "https",
host = "api.weixin.qq.com",
port = "443",
}
local scene_str = "abc"
local body = {
expire_seconds = 3600*24,
action_name = "QR_SCENE",
action_info = {
scene = {
scene_str = scene_str
}
}
}
local resBody, res, err = httpi:exec(options, function(httpc)
return httpc:request({
method = "POST",
path = path,
body = json.encode(body),
headers = {["Content-Type"] = "application/json",},
})
end)
if not res then
ngx.log(ngx.ERR, "=============>send message request failed: ", err)
return nil
end
log.notice(resBody)