[英]How to set timeout for a particular URL in rails
我使用機架超時,它工作正常。 但我無法弄清楚如何為特定的URL設置時間。
即使我喜歡:
map '/foo/bar' do Rack::Timeout.timeout = 10 end
不僅是/ foo / bar動作,而且每個動作都會在10秒后消失。
是否可以為特定URL設置超時? 或者我應該使用除機架超時之外的其他解決方案?
如果您擔心特定操作運行時間過長,我會將關注的代碼包裝在Timeout塊中,而不是嘗試在URL級別上強制執行超時。 您可以輕松地將下面的內容包裝到輔助方法中,並在整個控制器中使用變量超時。
require "timeout'"
begin
status = Timeout::timeout(10) {
# Potentially long process here...
}
rescue Timeout::Error
puts 'This is taking way too long.'
end
Jiten Kothari答案的更新版本:
module Rack
class Timeout
@excludes = [
'/statistics',
]
class << self
attr_accessor :excludes
end
def call_with_excludes(env)
#puts 'BEGIN CALL'
#puts env['REQUEST_URI']
#puts 'END CALL'
if self.class.excludes.any? {|exclude_uri| /\A#{exclude_uri}/ =~ env['REQUEST_URI']}
@app.call(env)
else
call_without_excludes(env)
end
end
alias_method_chain :call, :excludes
end
end
將此代碼作為timeout.rb放在config / initializers文件夾下,並將您的特定URL放在排除數組上
require RUBY_VERSION < '1.9' && RUBY_PLATFORM != "java" ? 'system_timer' : 'timeout'
SystemTimer ||= Timeout
module Rack
class Timeout
@timeout = 30
@excludes = ['your url here',
'your url here'
]
class << self
attr_accessor :timeout, :excludes
end
def initialize(app)
@app = app
end
def call(env)
#puts 'BEGIN CALL'
#puts env['REQUEST_URI']
#puts 'END CALL'
if self.class.excludes.any? {|exclude_uri| /#{exclude_uri}/ =~ env['REQUEST_URI']}
@app.call(env)
else
SystemTimer.timeout(self.class.timeout, ::Timeout::Error) { @app.call(env) }
end
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.