asynchronous http request in ruby

╄→гoц情女王★ 提交于 2019-11-27 21:04:39
apneadiving

Lightweight Async handling is the job of Threads (as you said) or Fibers.

Otherwise, you should consider EventMachine which is a very powerful tool.

EDIT: The above URL for Event Machine is dead. Here is their GitHub account, https://github.com/eventmachine/eventmachine . It serves as a good starting point.

Here is a great article covering the topic.

Generally, viable alternatives to using threads for this would be the use of a Fiber or you could use em-http-request. In the latter example you could leave out the callback handling for your particular purpose.

If its just about plain http requests in async style, probably Unirest is the best fit to achieve it.

Asnc request is as simple as:

response = Unirest.post "http://httpbin.org/post", 
                    headers:{ "Accept" => "application/json" }, 
                    parameters:{ :age => 23, :foo => "bar" } {|response|
response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!