如何在rails中生成异步http请求

时间:2015-11-10 08:47:45

标签: ruby http ruby-on-rails-4 asynchronous

在我的rails应用程序中,我需要向第三方服务发出http请求,因为http请求是同步的,有时需要超过20秒才能从它们获得响应。

我只是将一些数据推送到该服务,我不关心响应是什么,所以我想让请求异步,所以我的代码将继续执行而不被阻止。

我怎么能在ruby中做到?

2 个答案:

答案 0 :(得分:4)

您需要在ruby中使用Event Machine和Fibers。

Github: em-http-request

答案 1 :(得分:3)

  

我需要发出一个http请求...所以我的代码将继续执行而不会被阻止。

def some_action
  Thread.new do
    uri = URI('http://localhost:4567/do_stuff')
    Net::HTTP.post_form(uri, 'x' => '1', 'y' => '2')
  end

  puts "****Execution continues here--before the response is received."
end

这是一个可以用来测试它的sinatra应用程序:

1)$ gem install sinatra

2)

#my_sinatra_app.rb

require 'sinatra'

post '/do_stuff' do
  puts "received: #{params}" #Check the sinatra server window for the output.
  sleep 20  #Do some time consuming task.

  puts "Sending response..."
  "The result was: 30"   #The response(which the rails app ignores).
end

<强>输出

$ ruby my_sinatra_app.rb
== Sinatra (v1.4.6) has taken the stage on 4567 for development with backup from Thin
Thin web server (v1.6.4 codename Gob Bluth)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop

received: {"x"=>"1", "y"=>"2"}
<20 second delay>
Sending response...

127.0.0.1 - - [11/Nov/2015:12:54:53 -0400] "POST /do_stuff HTTP/1.1" 200 18 20.0032

当你导航到rails app中的some_action()时,rails服务器窗口将立即输出****Execution continues here--before the response is received.,sinatra服务器窗口将立即输出params哈希,其中包含数据在邮寄请求中发送。然后在20秒延迟后,sinatra服务器窗口将输出Sending response...