Module: Mongoid::Collections::Retry

Included in:
Master, Mongoid::Cursor
Defined in:
lib/mongoid/collections/retry.rb

Overview

Provides behaviour for retrying commands on connection failure.

Instance Method Summary collapse

Instance Method Details

#retry_on_connection_failureObject

Retries command on connection failures.

This is useful when using replica sets. When a primary server wents down and a command is issued, the driver will raise a Mongo::ConnectionFailure. We wait a little bit, because nodes are electing themselves, and then retry the given command.

By setting Mongoid.max_retries_on_connection_failure to a value of 0, no attempt will be made, immediately raising connection failure. Otherwise it will attempt to make the specified number of retries and then raising the exception to clients.

Examples:

Retry the command.

retry_on_connection_failure do
  collection.send(name, *args)
end

Since:

  • 2.0.0



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mongoid/collections/retry.rb', line 26

def retry_on_connection_failure
  retries = 0
  begin
    yield
  rescue Mongo::ConnectionFailure => ex
    retries = increase_retry_attempts(retries, ex)
    retry
  rescue Mongo::OperationFailure => ex
    if ex.message =~ /not master/
      Mongoid.reconnect!
      retries = increase_retry_attempts(retries, ex)
      retry
    else
      raise ex
    end
  end
end