Class: Monga::Clients::ReplicaSetClient

Inherits:
Object
  • Object
show all
Defined in:
lib/monga/clients/replica_set_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ ReplicaSetClient

ReplicaSetClient creates SingleInstanceClient to each server. Accepts

  • servers - you could pas them as a array of servers ([‘1.1.1.1:27017’, ‘1.1.1.2:27017’]), or as a array of hashes: ([‘1.1.1.1’, port: 27017, ‘1.1.1.2’, port: 27017])

  • read_pref - read preferrence (:primary, :primary_preferred, :secondary, :secondary_preferred)

  • pool_size - connection pool size to each server

  • type - connection type (:em/:sync/:block)



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/monga/clients/replica_set_client.rb', line 11

def initialize(opts)
  @timeout = opts[:timeout]
  @read_pref = opts[:read_pref] || :primary

  servers = opts.delete :servers
  @clients = servers.map do |server|
    case server
    when Hash
      Monga::Clients::SingleInstanceClient.new(opts.merge(server))
    when String
      h, p = server.split(":")
      o = { host: h, port: p.to_i }
      Monga::Clients::SingleInstanceClient.new(opts.merge(o))
    end
  end

  @proxy_connection = Monga::Connection.proxy_connection_class(opts[:type], self)
end

Instance Attribute Details

#clientsObject (readonly)

Returns the value of attribute clients.



3
4
5
# File 'lib/monga/clients/replica_set_client.rb', line 3

def clients
  @clients
end

#read_prefObject (readonly)

Returns the value of attribute read_pref.



3
4
5
# File 'lib/monga/clients/replica_set_client.rb', line 3

def read_pref
  @read_pref
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



3
4
5
# File 'lib/monga/clients/replica_set_client.rb', line 3

def timeout
  @timeout
end

Instance Method Details

#aquire_connectionObject

Aquires connection due to read_pref option



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/monga/clients/replica_set_client.rb', line 31

def aquire_connection
  server = case @read_pref
  when :primary
    primary
  when :secondary
    secondary
  when :primary_preferred
    primary || secondary
  when :secondary_preferred
    secondary || primary
  when :nearest
    raise ArgumentError, "nearest read preferrence is not implemented yet"
  else
    raise ArgumentError, "`#{@read_pref}` is not valid read preferrence, use :primary, :primary_preferred, :secondary, or :secondary_preferred"
  end

  server || @proxy_connection
end

#primaryObject

Fetch primary server



51
52
53
54
# File 'lib/monga/clients/replica_set_client.rb', line 51

def primary
  pr = @clients.detect{ |c| c.primary? && c.connected? }
  pr.aquire_connection if pr
end

#secondaryObject

Fetch secondary server



57
58
59
60
# File 'lib/monga/clients/replica_set_client.rb', line 57

def secondary
  sc = @clients.select{ |c| c.secondary? && c.connected? }.sample
  sc.aquire_connection if sc
end