方法
實例公開方法
rate_limit(to:, within:, by: -> { request.remote_ip } 連結
將速率限制套用至透過標準 before_action
篩選器指定的全部動作,或透過 only:
和 except:
加以指定的動作。
針對 to:
所指定的請求數目上限,以及 within:
所設定的時間範圍予以限制。
速率限制預設是針對提出請求的 IP 位址而設,但你可以透過在 by:
參數中傳遞一個可呼叫函數,來提供你自己的身分函數。此函數會在處理請求的控制器背景下加以評估。
超出速率限制的請求,將會以 429 請求太多
回應加以拒絕。你可以透過在 with:
參數中傳遞一個可呼叫函數,來將此回應加以專業化。此函數會在處理請求的控制器背景下加以評估。
速率限制仰賴後端的 ActiveSupport::Cache
儲存庫,其預設設定值為 config.action_controller.cache_store
,而此設定值本身的預設值則為全域性的 config.cache_store
。如果你不想將速率限制儲存在與一般快取存放同一處的資料儲存庫中,則可以在 store
參數中傳遞自訂儲存庫。
如果你想對每個控制器使用多重速率限制,則需要透過 name:
選項,為每個限制指定顯式名稱。
範例
class SessionsController < ApplicationController
rate_limit to: 10, within: 3.minutes, only: :create
end
class SignupsController < ApplicationController
rate_limit to: 1000, within: 10.seconds,
by: -> { request.domain }, with: -> { redirect_to busy_controller_url, alert: "Too many signups on domain!" }, only: :new
end
class APIController < ApplicationController
RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(url: ENV["REDIS_URL"])
rate_limit to: 10, within: 3.minutes, store: RATE_LIMIT_STORE
end
class SessionsController < ApplicationController
rate_limit to: 3, within: 2.seconds, name: "short-term"
rate_limit to: 10, within: 5.minutes, name: "long-term"
end
# File actionpack/lib/action_controller/metal/rate_limiting.rb, line 55 def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, name: nil, **options) before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store, name: name) }, **options end