套接字http lua设置超时

时间:2020-06-30 11:04:37

标签: api rest lua timeout

我正在尝试创建一个可以使用http套接字lua调用REST的函数。 我试图以此方式设置超时时间。但是,当我运行此功能时,超时未运行。我应该如何设置超时时间?

local http = require "socket.http"
local socket = require "socket"
       
       local respbody = {} 
       http.request {
                     method = req_method,
                     url = req_url,
                     source = ltn12.source.string(req_body),
                     headers = 
                              {
                                ["Content-Type"] = req_content_type,
                                ["content-length"] = string.len(req_body),
                                ["Host"] = host,

                              },
            
                     sink = ltn12.sink.table(respbody),
                     create = function()
                         local req_sock = socket.tcp()
                         req_sock:settimeout(3, 't')
                         return req_sock
                     end,

}

3 个答案:

答案 0 :(得分:0)

您可能要检查lua-http。我用它来称呼REST并像魅力一样工作。我不是专家,但据我所知,这是一个很好的LUA http实现。

您可以设置两秒钟的超时时间,方法很简单:

local http_client = require "http.client"
local myconnection = http_client.connect {
    host = "myrestserver.domain.com";
    timeout = 2;
}

here中的完整文档。

答案 1 :(得分:0)

如果我根据自己的要求实施示例,会是这样吗? cmiiw

local http_client = require "http.client" 
local req_body = "key1=value1&key2=value2" 
local myconnection = http_client.connect { 
    method = "POST"; 
    url = "myrestserver.domain.com/api/example"; 
    host = "myrestserver.domain.com"; 
    source = req_body 
    headers = { 
       ["Content-Type"] = "application/x-www-form-urlencoded", 
       ["content-length"] = string.len(req_body), 
    }, 
    timeout = 2; 
}

答案 2 :(得分:0)

LuaSocket将http.TIMEOUT隐式设置为套接字对象。 另外,您还必须记住,套接字超时与请求超时不同。 套接字超时意味着每个操作的超时独立。在简单的情况下,您可以等待最多timeout秒的连接,然后每次读取操作最多可能需要timeout秒。而且由于HTTP客户端逐行读取响应,因此每个标头加上每个正文块将获得timeout秒。同样,可能存在重新定向,其中每个重定向都是单独的HTTP请求/响应。如果您使用TLS,则连接后还会发生握手,这也需要执行多次发送/接收操作。

我没有使用lua-http模块,也不知道在那里如何实现超时。 但是如果确实需要限制请求超时,我更喜欢使用cURL之类的模块。

相关问题