我最近在升级到Rails3时从混杂切换到瘦,在切换之前,我们一直在使用EventMachine,没有任何问题。在切换到thin之后,每当调用EventMachine时,服务器都会崩溃,并告诉我们返回的变量为nil。
据我所知,thin使用了EventMachine,这可能会导致与Mongrel使用的实现冲突。我使用EventMachine的次数不多,但我似乎需要在另一个实例中运行EventMachine,以便将它与thin使用的EventMachine分开。我在正确的轨道上吗?我如何让它在独立于Thin的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发布于 2012-01-28 05:25:04
Thin已经提供并管理了一个EventMachine反应器,因此您不需要单独设置一个。我认为对于初学者来说,您不需要将此代码嵌入到EventMachine.run {}块中。
在这里,您的方法有一些问题。首先,返回的@response变量将始终为空,因为EventMachine::HttpRequest是异步发生的,并且在命中http.callback {}块之前不会提供任何数据。其次,在每个EventMachine::HttpRequest回调中,都调用了EventMachine.stop。这将产生停止thin why服务器的效果,这可能是您看到服务器爆炸的原因。
如果您试图在rails应用程序中运行这类代码,则可能需要找到一种异步处理调用的方法,以便应用程序在等待长时间运行的进程发生时不会挂起。为此,我使用的一个好方法是使用Sinatra,它有一个async插件,允许您持有打开的长时间运行的请求。然后,您可以使用rails metal将其包含在您的rails3应用程序中,这样对您的异步/事件机器代码的请求就会被路由到sinatra。
https://stackoverflow.com/questions/9022991
复制相似问题