我可以使用 Ruby 的 Typhoeus 发出异步请求吗?

Can I make asynchronous requests with Ruby's Typhoeus?

我正在使用 Typhoeus 并希望发出单个请求而不阻塞响应。稍后,我可能会检查响应,也可能不会。关键是我不希望代码执行等待响应。

Typhoeus 有内置的方法吗?

不然估计得用线程自己搞了?

您可以尝试使用 thread:

response = nil

request_thread = Thread.new {
  # Set up the request object here
  response = request.response
}

从那里你可以检查 response == nil 看看请求是否已经发出,你可以调用 request_thread.join 阻塞直到线程完成执行。

我建议查看 'unirest' gem 以获得 Ruby。

据我所知,斑疹伤寒会阻塞 'hydra.run' 呼叫

使用 Unirest,它不会阻塞 get / post / put / etc 调用,而是继续 运行。如果需要,您可以将 'object' 存储在散列或带有标识符的数组中,以便稍后检索,如下所示:

identifier_requests['id'] = Unirest.post(url,headers: headers, parameters: param, auth: auth)

然后要阻止或检索响应,请使用对响应对象的调用之一:

response_code = (identifier_requests['id']).code
response.body

http://unirest.io/ruby.html

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

这是他们在 https://github.com/typhoeus/typhoeus

的文档