分片选择器中间件
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
}
方法
属性
[R] | options | |
[R] | resolver |
类公共方法
new(app, resolver, options = {}) 链接
源代码: 显示 | 在 GitHub 上
# 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) 链接
源代码: 显示 | 在 GitHub 上
# 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