我有一个使用 Thin 运行的模块化 Sinatra 网络应用程序,EventMachine 运行其他任务。
它可以工作,但网络服务器有些奇怪:任何请求,无论是成功的还是 404 错误,都不会出现在 Thin/Sinatra 的日志输出中。当我取消该过程时,服务器会结束两次。
这是应用程序的粗略基本结构:
简介:
web: ruby app.rb
应用.rb:
require 'thin'
require 'eventmachine'
require 'app/frontend'
EM.run do
# Start some background tasks here...
EM.add_periodic_timer(1200) do
# Do a repeating task here...
end
App::Frontend.run!
end
应用程序/frontend.rb:
require 'sinatra/base'
module App
class Frontend < Sinatra::Base
get '/' do
# Display page
end
# etc
end
end
当我执行 foreman start
时,我得到:
16:50:00 web.1 | started with pid 76423
16:50:01 web.1 | [messages about EventMachine background tasks starting]
16:50:01 web.1 | == Sinatra/1.4.3 has taken the stage on 5000 for development with backup from Thin
16:50:01 web.1 | >> Thin web server (v1.5.1 codename Straight Razor)
16:50:01 web.1 | >> Maximum connections set to 1024
16:50:01 web.1 | >> Listening on 0.0.0.0:5000, CTRL+C to stop
当我请求现有网页(加载正常)或不存在的网页时,不再输出任何内容。当我取消这个过程时,我得到:
^CSIGINT received
16:50:08 system | sending SIGTERM to all processes
SIGTERM received
16:50:08 web.1 | >> Stopping ...
16:50:08 web.1 | == Sinatra has ended his set (crowd applauds)
16:50:08 web.1 | >> Stopping ...
16:50:08 web.1 | == Sinatra has ended his set (crowd applauds)
16:50:08 web.1 | exited with code 0
Sinatra 完成两次让我觉得我以某种方式运行了两次,并且没有记录为网页提供服务的那个......但我不知道我是如何管理它的!
最佳答案
docs on Modular vs. Classic style提到默认设置有一些更改,其中之一是日志记录,默认情况下它是关闭的。
添加settings.logging = true
到 class Frontend < Sinatra::Base
的顶部在我的终端窗口中为 localhost:5000 请求提供一个日志。
我不认为第二个问题是它创建了两个进程,而是它在关闭服务器之前终止并重新启动进程。这可以通过遵循将 EventMachine 与 Sinatra 结合使用的 Sinatra 配方来解决,这比您所做的要复杂一些。这是他们的代码,经过修改以适合您的应用:
新app.rb
:
EM.run do
server = 'thin'
host = '0.0.0.0'
port = ENV['PORT'] || '8181'
web_app = App::Frontend.new
# Start some background tasks here...
EM.add_periodic_timer(1200) do
# Do a repeating task here...
end
dispatch = Rack::Builder.app do
map '/' do
run web_app
end
end
Rack::Server.start({
app: dispatch,
server: server,
Host: host,
Port: port
})
end
( original source, from Sinatra Recipes )
ENV['PORT']
的使用在 app.rb 中,您可以在工头中使用多个实例(例如 foreman start -p 4000 -c web=2
,它将在端口 4000 和 4001 上运行服务)。并且它们都出现在日志中!
希望对您有所帮助。
关于ruby - 使用 Thin 和 EventMachine 运行模块化 Sinatra 应用程序。启动两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516053/