async_sinatra 请求会因 em-http 而静默崩溃。我该如何解决这个问题?

发布于 2024-10-11 22:44:00 字数 800 浏览 8 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尹雨沫 2024-10-18 22:44:00

如果您的 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.

西瑶 2024-10-18 22:44:00

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 call EM.run explicitly, as Sinatra is already operating within an EventMachine loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文