如何在rails中发出异步http请求

fuy*_*uyi 5 ruby asynchronous http ruby-on-rails-4

在我的 rails 应用程序中,我需要向 3rd 方服务发出 http 请求,因为 http 请求是同步的,有时需要超过 20 秒才能从他们那里得到响应。

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

我怎么能用红宝石做呢?

7st*_*tud 6

我需要发出一个 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
Run Code Online (Sandbox Code Playgroud)

这是一个 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
Run Code Online (Sandbox Code Playgroud)

输出

$ 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
Run Code Online (Sandbox Code Playgroud)

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


Rub*_*ith 4

您需要在 ruby​​ 中使用事件机和纤维。

Github:em-http-request