您可以在 eventmachine 中挂载 Sinatra 应用程序(为您提供支持 EM 的网络服务器,即 Thin)。然后,您应该可以从您的 Sinatra 应用程序完全访问 EM 反应器循环,并允许任何其他 EM 插件也可以运行。
Sinatra 食谱有一个很好的例子:
http://recipes.sinatrarb.com/p/embed/event-machine
这是代码的一个非常精简的版本:
require 'eventmachine'
require 'sinatra/base'
require 'thin'
def run(opts)
EM.run do
server = opts[:server] || 'thin'
host = opts[:host] || '0.0.0.0'
port = opts[:port] || '8181'
web_app = opts[:app]
dispatch = Rack::Builder.app do
map '/' do
run web_app
end
end
unless ['thin', 'hatetepe', 'goliath'].include? server
raise "Need an EM webserver, but #{server} isn't"
end
Rack::Server.start({
app: dispatch,
server: server,
Host: host,
Port: port
})
end
end
class HelloApp < Sinatra::Base
configure do
set :threaded, false
end
get '/hello' do
'Hello World'
end
get '/delayed-hello' do
EM.defer do
sleep 5
end
'I\'m doing work in the background, but I am still free to take requests'
end
end
run app: HelloApp.new