【问题标题】:Request to Grape API for rails block other requests对 Rails 的 Grape API 的请求会阻止其他请求
【发布时间】:2015-07-23 04:04:25
【问题描述】:

对于我的 rails 应用程序,我使用 gem Grape 设置了一个 API。我添加了一个测试 post 方法,代码休眠 10 秒并返回 {'status'=>'success'}。除了 API 调用似乎阻止发送到服务器的所有其他请求之外,一切正常。在此 sleep 10 seconds 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

【问题讨论】:

    标签: ruby-on-rails-4 grape grape-api


    【解决方案1】:

    这意味着您的请求不会同时并行处理。 在 Rails 4 中启用了线程安全,这可能与此有关。 Threadsafe 可能会锁定您的操作,因此您的下一个请求无法获得访问权限。但是,您可以明确告诉服务器处理同时请求。在所有配置/环境文件中添加这一行会有所帮助。

    config.allow_concurrency = true

    此外,您还需要一个可以像 puma 一样处理并发的服务器。

    更多信息来自 herehere

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-11
      • 2020-09-22
      • 2015-06-22
      • 1970-01-01
      • 2015-08-25
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多