async_sinatra 请求会因 em-http 而静默崩溃。我该如何解决这个问题?
我有以下代码:
require 'rubygems'
require 'eventmachine'
require 'em-http'
require 'sinatra/base'
require 'sinatra/async'
class Api < Sinatra::Base
register Sinatra::Async
aget '/1' do
EventMachine.run {
http = EventMachine::HttpRequest.new( "http://www.google.com").get(:timeout => 5)
http.callback { puts "h2" ;ret_val = http.response; EventMachine.stop}
http.errback {puts "was h2ere1" ;ret_val = nil; EventMachine.stop}
}
body "done processing 1"
end
aget '/2' do
body "done processing 2"
end
end
当我发出以下请求时,它运行良好:
curl http://localhost:3000/2
但是,当我发出以下请求时,它会打印“h2”并且应用程序默默退出:
curl http://localhost:3000/1
任何帮助将不胜感激。谢谢!
I have the following code:
require 'rubygems'
require 'eventmachine'
require 'em-http'
require 'sinatra/base'
require 'sinatra/async'
class Api < Sinatra::Base
register Sinatra::Async
aget '/1' do
EventMachine.run {
http = EventMachine::HttpRequest.new( "http://www.google.com").get(:timeout => 5)
http.callback { puts "h2" ;ret_val = http.response; EventMachine.stop}
http.errback {puts "was h2ere1" ;ret_val = nil; EventMachine.stop}
}
body "done processing 1"
end
aget '/2' do
body "done processing 2"
end
end
When I issue the following, it works well:
curl http://localhost:3000/2
But, when I issue the following request, it prints "h2" and the application silently quits:
curl http://localhost:3000/1
Any help will be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的 Web 服务器(例如 Thin)基于 EventMachine,则 EventMachine.stop 行实际上会停止 Web 服务器以及由 EventMachine.run 创建的 EventMachine 实例。
我找不到一种方法来阻止这样的嵌套 EventMachines。我的建议 - 使用 Weary 或其他非阻塞 HTTP 请求库。
If your web server (Eg. thin) is based on EventMachine, then the EventMachine.stop line will actually stop the webserver as well as the EventMachine instance created by EventMachine.run.
I can't find a way to stop nested EventMachines like this. My advice - use Weary or another non-blocking HTTP request library.
Sinatra::Async 提供了它自己的
body
帮助器,需要从 EventMachine 循环内调用。另外值得注意的是:如果您通过 Thin 运行 Sinatra,则不应显式调用EM.run
,因为 Sinatra 已经在 EventMachine 循环内运行。Sinatra::Async provides it's own
body
helper that needs to be called from within the EventMachine loop. Also worth noting: if you're running Sinatra through Thin, you shouldn't callEM.run
explicitly, as Sinatra is already operating within an EventMachine loop.