代码之家  ›  专栏  ›  技术社区  ›  yegor256

如何从sinatra配置瘦web服务器?

  •  2
  • yegor256  · 技术社区  · 6 年前

    这是我的Web应用:

    class Front < Sinatra::Base
      configure do
        set :server, :thin
      end
      get '/' do
        'Hello, world!'
      end 
    end
    

    我是这样开始的:

    Front.start!
    

    工作很好,但我想配置瘦为“线程”。我知道这是可能的,根据 their documentation . 但我不知道怎么通过 threaded: true 参数设置为thin。我试过但没用:

    configure do
      set :server_settings, threaded: true
    end
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   anothermh ScarletMerlin    6 年前

    按照您描述的方式启动时,瘦web服务器在默认情况下是线程化的。

    # thin_test.rb
    require 'sinatra/base'
    
    class Front < Sinatra::Base
      configure do
        set :server, :thin
      end
    
      get '/' do
        'Hello, world!'
      end 
    
      get '/foo' do
        sleep 30
        'bar'
      end
    end
    
    Front.start!
    

    开始:

    ruby thin_test.rb
    

    确认方式:

    # will hang for 30 seconds while sleeping
    curl localhost:4567/foo
    
    # will complete successfully while the other request is pending
    curl localhost:4567
    Hello, world!
    

    this answer 关于sinatra如何使用其他web服务器。

    如果这不起作用的原因,它可能会一起黑客的东西 server_settings 选项,该选项通常仅对Webrick有用,除非您使用一些未记录的方式强制执行它:

    require 'sinatra/base'
    require 'thin'
    
    class ThreadedThinBackend < ::Thin::Backends::TcpServer
      def initialize(host, port, options)
        super(host, port)
        @threaded = true
      end
    end
    
    class Front < Sinatra::Base
      configure do
        set :server, :thin
    
        class << settings
          def server_settings
            { :backend => ThreadedThinBackend }
          end
        end
      end
    
      get '/' do
        'Hello, world!'
      end 
    
      get '/foo' do
        sleep 30
        'foobar'
      end
    end
    
    Front.start!
    

    我很难判断这个例子是否是线程化的原因,因为它默认以线程模式启动。也就是说,它不会引发异常,并以线程模式运行:

    #会在睡觉时悬挂30秒
    curl本地主机:4567/foo
    
    #将在其他请求挂起时成功完成
    curl本地主机:4567
    你好,世界!
    

    有关的详细信息 服务器设置 可以找到 here , here here .