2012-01-26 62 views
2

我最近从mongrel切换到thin时升级到rails 3.在切换之前,我们一直使用EventMachine没有任何问题。切换到精简之后,无论何时调用EventMachine,服务器都会弹出并说我们返回的变量为零。使用EventMachine和Thin

从我所了解的薄利用EventMachine这可能会导致与Mongrel一起使用的实现冲突。我还没有用过很多EventMachine,但似乎需要在另一个实例中运行EventMachine,以将它与正在使用的EventMachine分开。我在正确的轨道上吗?我如何才能在Thin's EventMachine之外独立运行它?

这里是EventMachine的一个片段,我们目前已经实现

def connect 
    EventMachine.run { 
    args, options = { 
    :query => @options[:query], 
     :head => @options[:headers] 
    }, { 
     :connect_timeout => @options[:timeout], 
     :inactivity_timeout => @options[:timeout] 
    } 

    args[:body] = @options[:data] if allow_body? 
    args[:redirects] = @options[:redirects] if @options[:redirects] 

    http = EventMachine::HttpRequest.new(@uri, options).send(@options[:method], args) 

    http.errback { 
     @response = HttpConnection::Response.new(http, false, @options[:logger]) 

     EventMachine.stop 
    } 

    http.callback { 
     @response = HttpConnection::Response.new(http, true, @options[:logger]) 

     EventMachine.stop 
    } 
    } 

    return @response 
end 

回答

3

薄已经提供并管理EventMachine的反应器,所以你不需要设置一个seperately。我认为您不需要将此代码嵌入EventMachine.run {}区块中供初学者使用。

您的方法在这里有几个问题。首先,返回的@response变量将始终为零,因为EventMachine::HttpRequest是异步发生的,并且在您点击http.callback {}块之前不会给您任何数据。其次,在每个EventMachine::HttpRequest回调中,您都会打电话给EventMachine.stop。这会导致停止thin网络服务器,这可能是您看到服务器爆炸的原因。

如果您试图在rails应用程序中运行此类代码,您可能需要找到一种异步处理调用的方法,以便应用程序在等待长时间运行的进程时不会挂起发生。我用过的一个好方法是使用Sinatra,它有一个async插件,允许你保存开放的长时间运行的请求。然后,您可以使用rails metal将它包含在rails3应用程序中,以便将异步/事件机器代码的请求路由到sinatra。

+0

你说得对,Thin已经提供了一个EM反应器。而且EM.stop会发出信号减弱以停止!我决定彻底放弃这个EM实现,因为它看起来不正确。我会看看使用Sinatra和异步插件。谢谢丹 –