在lua中操作http請求有兩種方式

Ruthless發表於2022-08-26

第一種方式:使用透過ngx.location.capture 去方式實現,但是有一些限制
第二種方式:因為openresty預設沒有引入第三方http客戶端類庫lua-resty-http,需要下載(推薦)。

下載lua-resty-http類庫

wget https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty/http_headers.lua
wget https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty/http.lua
wget https://github.com/ledgetech/lua-resty-http/blob/master/lib/resty/http_connect.lua

 lua-resty-http語法:

local res, err = httpc:request_uri(uri, {  
    method = "POST/GET",  ---請求方式
    query = str,  ---get方式傳引數
    body = str,     ---post方式傳引數
    path = "url" ----路徑
    headers = {  ---header引數
        ["Content-Type"] = "application/json",  
    }  
})

 

把http_headers.lua、http.lua、http_connect.lua檔案放在D:\dev\openresty-1.19.9.1\lualib\resty目錄,有重複直接覆蓋。

location /test {
    default_type text/html;
    content_by_lua_file lua/http_test.lua;
}

 

D:\dev\openresty-1.19.9.1\lua\http_test.lua,內容如下:

local http = require("resty.http")
--建立http客戶端例項
local httpc = http:new()

local resp,err = httpc:request_uri("http://issm.suning.com",
{
    method = "GET",
    path="/productDetail_P11271.htm",
    headers = {["User-Agent"]="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"}
})
if not resp then
    ngx.say("request error:",err)
    return
end
--獲取狀態碼
ngx.status = resp.status

--獲取響應資訊
--響應頭中的Transfer-Encoding和Connection可以忽略,因為這個資料是當前server輸出的。
for k,v in pairs(resp.headers) do
    if k ~= "Transfer-Encoding" and k ~= "Connection" then
        ngx.header[k] =v
    end
end

--響應體
ngx.say(resp.body)

httpc:close()

 

注意:需要在http模組中新增如下指令來做DNS解析,不然會報出解析域名錯誤,如下:

2022/08/26 09:33:21 [info] 8248#21972: *277 client timed out (10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) while waiting for request, client: 127.0.0.1, server: 0.0.0.0:80

解決辦法:resolver 8.8.8.8;

其http客戶端也支援連線池,與redis、mysql連線池配置一致。

相關文章