如何 运行 没有其他任何东西的多个 Sinatra 实例?

How to run multiple Sinatra instances without anything else?

我想生成很多可配置的 Sinatra 服务器。
例如:

require 'sinatra/base'
class AwesomeOne
    def initialize port
        @sapp = Sinatra.new {
            set :port => port
            get '/'do
                "Hi!"
            end
        }
    end
    def run!
        @sapp.run!
    end
end

然后:

ths = []
(1111..9999).each { |port|
    ths.push Thread.new { AwesomeOne.new(port).run! }
}

但出了点问题:我无法访问每个页面。但其中一些似乎可以访问。

那么,如何在一个 .rb 文件中多次 运行 Sinatra?

我刚好需要同样的东西,所以我做了一些研究。 你可以使用Sinatra的级联、路由或中间件选项,参见https://www.safaribooksonline.com/library/view/sinatra-up-and/9781449306847/ch04.html并搜索'multiple',我建议你买本书阅读,都是非常有用的东西!

但更倾向于您的方法,您可以使用事件机器 Sinatra 已经用于 运行 不同端口上的多个应用程序,Ruby 本身仅启动一次。 有关解释和更多示例,请参阅 http://recipes.sinatrarb.com/p/embed/event-machine。我把这个例子和你的代码结合起来了。

# adapted from 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,
      signals: false,
    })
  end
end

class HelloApp < Sinatra::Base
  configure do
    set :threaded, true
  end

  get '/hello' do
    "Hello World from port #{request.port}"
  end
end

ths = []
(4567..4569).each do |port|
  ths.push Thread.new { run app: HelloApp.new, port: port }
end

ths.each{|t| t.join}

产出

Thin web server (v1.6.3 codename Protein Powder)
Maximum connections set to 1024
Listening on 0.0.0.0:4567, CTRL+C to stop
Thin web server (v1.6.3 codename Protein Powder)
Maximum connections set to 1024
Listening on 0.0.0.0:4568, CTRL+C to stop
Thin web server (v1.6.3 codename Protein Powder)
Maximum connections set to 1024
Listening on 0.0.0.0:4569, CTRL+C to stop

在 windows cmd netstat -ab 中给出

TCP    0.0.0.0:4567           ******:0              LISTENING
TCP    0.0.0.0:4568           ******:0              LISTENING
TCP    0.0.0.0:4569           ******:0              LISTENING

所有端口上的 hello 示例都有效。