略過前往內文 略過前往搜尋

分片選擇器中介軟體

ShardSelector Middleware 提供一個自動變換分片的架構。Rails 提供一個基礎架構來決定要切換到哪個分片,並允許應用程式在需要時撰寫自訂的變換策略。

ShardSelector 使用一組選項(目前僅支援 lock),中介軟體可以用來改變行為。預設情況下,lock 為 true,且會禁止要求在區塊內部一但切換分片。如果 lock 為 false,則會允許切換分片。對於基於租戶的分片,lock 應該始終為 true,以防止應用程式程式碼錯誤地切換租戶。

可以在設定檔中設定選項

config.active_record.shard_selector = { lock: true }

應用程式也必須提供解析器的程式碼,因為它依賴於應用程式特定模型。一個範例的解析器如下所示

config.active_record.shard_resolver = ->(request) {
  subdomain = request.subdomain
  tenant = Tenant.find_by_subdomain!(subdomain)
  tenant.shard
}
方法
C
N

屬性

[R] options
[R] resolver

類別公開的方法

new(app, resolver, options = {})

# File activerecord/lib/active_record/middleware/shard_selector.rb, line 32
def initialize(app, resolver, options = {})
  @app = app
  @resolver = resolver
  @options = options
end

實體公開的方法

call(env)

# File activerecord/lib/active_record/middleware/shard_selector.rb, line 40
def call(env)
  request = ActionDispatch::Request.new(env)

  shard = selected_shard(request)

  set_shard(shard) do
    @app.call(env)
  end
end