在我的 Rails 应用程序中,我需要向 3rd 方服务发出 http 请求,因为 http 请求是同步的,有时需要超过 20 秒才能从他们那里得到响应。
我只是向该服务推送一些数据,我不关心响应是什么,所以我想让请求异步,这样我的代码将继续执行而不会被阻塞。
我怎么能用 ruby 做到这一点?
最佳答案
I need to make a http request...so my code will continue execution and not been blocked.
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 应用程序中的 some_action()
时,rails 服务器窗口将立即输出 ****Execution continues here--before received response.
,sinatra服务器窗口会立即输出params
散列,其中包含post请求中发送的数据。然后在延迟 20 秒后,sinatra 服务器窗口将输出 Sending response...
。
关于ruby - 如何在 Rails 中发出异步 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33625972/