请求Grape API阻止Rails块其他请求

4
对于我的Rails应用程序,我使用了Grape gem来设置一个API。我添加了一个测试post方法,该代码需要休眠10秒钟并返回 {'status' => 'success'}。除了API调用会阻塞所有发送到服务器的其他请求外,一切正常。任何其他请求都不会被执行,直到这个睡眠10秒的API完成。任何来自前端界面的GET请求都将延迟。如果我模拟了两个API调用,第二个调用需要20秒钟(10秒钟等待第一个完成)才能完成。请给出建议。
api.rb文件如下:
module ProjectName
  module MyErrorFormatter
    def self.call message, backtrace, options, env
      { "status" => "Fail", "error_message" => message }.to_json
    end
  end

  class API < Grape::API

    format :json
    default_format :json
    prefix 'api'
    cascade false
    error_formatter :json, MyErrorFormatter
    helpers APIHelpers

    before do 
      authenticate!
    end

    post do
      if params[:action].present?
        p_url = format_url(params)
        redirect "/api/#{params[:action]}?key=#{params[:key]}#{p_url}"
      end
    end

    post 'test' do
      sleep(10)
      {'status'=>'success'}
    end
  end
end

我正在使用Rails 4.2.0版本

1个回答

2
这意味着你的请求不会同时并行处理。Rails 4 中启用了 threadsafe,这可能与此有关。Threadsafe 可能会锁定你的操作,因此下一个请求无法访问。但是,你可以明确地告诉服务器处理同时请求。在所有的 config/environments 文件中添加这一行将有所帮助。 config.allow_concurrency = true 此外,你需要一个能够处理并发的服务器,如 puma。
更多信息请参见这里这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接