class ActiveRecord::Middleware::DatabaseSelector::Resolver
:nodoc:
if it’s been 2 seconds since the last write.
By default the Resolver class will send read traffic to the replica
be changed.
DatabaseSelector::Resolver and implements the methods that need to
create a custom resolver class that inherits from
To change the behavior of the Resolver class in your application,
determine which database the request should use.
The Resolver class is used by the DatabaseSelector middleware to
def self.call(context, options = {})
def self.call(context, options = {}) new(context, options) end
def initialize(context, options = {})
def initialize(context, options = {}) @context = context @options = options @delay = @options && @options[:delay] ? @options[:delay] : SEND_TO_REPLICA_DELAY @instrumenter = ActiveSupport::Notifications.instrumenter end
def read(&blk)
def read(&blk) if read_from_primary? read_from_primary(&blk) else read_from_replica(&blk) end end
def read_from_primary(&blk)
def read_from_primary(&blk) ActiveRecord::Base.connected_to(role: ActiveRecord.writing_role, prevent_writes: true) do instrumenter.instrument("database_selector.active_record.read_from_primary", &blk) end end
def read_from_primary?
def read_from_primary? !time_since_last_write_ok? end
def read_from_replica(&blk)
def read_from_replica(&blk) ActiveRecord::Base.connected_to(role: ActiveRecord.reading_role, prevent_writes: true) do instrumenter.instrument("database_selector.active_record.read_from_replica", &blk) end end
def send_to_replica_delay
def send_to_replica_delay delay end
def time_since_last_write_ok?
def time_since_last_write_ok? Time.now - context.last_write_timestamp >= send_to_replica_delay end
def update_context(response)
def update_context(response) context.save(response) end
def write(&blk)
def write(&blk) write_to_primary(&blk) end
def write_to_primary
def write_to_primary ActiveRecord::Base.connected_to(role: ActiveRecord.writing_role, prevent_writes: false) do instrumenter.instrument("database_selector.active_record.wrote_to_primary") do yield ensure context.update_last_write_timestamp end end end