我正在使用 Typhoeus 并想发出一个请求而不阻塞响应。稍后,我可能会检查响应,或者我可能不会。关键是我不希望代码执行等待响应。
Typhoeus 有内置的方法吗?
否则我想我必须使用线程并自己做?
您可以尝试使用线程:
response = nil
request_thread = Thread.new {
# Set up the request object here
response = request.response
}
从那里你可以检查response == nil
请求是否已经发出,你可以调用request_thread.join
阻塞直到线程完成执行。
我建议研究 Ruby 的“unirest”gem。
据我所知,Typhoeus 阻止了“hydra.run”调用
使用 Unirest,它不会阻塞 get/post/put/etc 调用,而是继续运行。如果需要,您可以将“对象”存储在散列或带有标识符的数组中,以便稍后检索,如下所示:
identifier_requests['id'] = Unirest.post(url,headers: headers, parameters: param, auth: auth)
然后要阻止或检索响应,请使用响应对象上的调用之一:
response_code = (identifier_requests['id']).code
response.body
Typhoeus 内置了非阻塞调用。从他们的文档中:
request = Typhoeus::Request.new("www.example.com", followlocation: true)
request.on_complete do |response|
if response.success?
# hell yeah
elsif response.timed_out?
# aw hell no
log("got a time out")
elsif response.code == 0
# Could not get an http response, something's wrong.
log(response.return_message)
else
# Received a non-successful http response.
log("HTTP request failed: " + response.code.to_s)
end
end
request.run