Select secondary read node randomly

This commit is contained in:
Kyle Banker 2010-11-19 18:26:38 -05:00
parent 1e57ca90e1
commit add9779fa0
1 changed files with 21 additions and 17 deletions

View File

@ -39,7 +39,7 @@ module Mongo
MONGODB_URI_SPEC = "mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/database]" MONGODB_URI_SPEC = "mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/database]"
attr_reader :logger, :size, :nodes, :auths, :primary, :secondaries, :arbiters, attr_reader :logger, :size, :nodes, :auths, :primary, :secondaries, :arbiters,
:safe, :primary_pool, :secondary_pools :safe, :primary_pool, :read_pool
# Counter for generating unique request ids. # Counter for generating unique request ids.
@@current_request_id = 0 @@current_request_id = 0
@ -143,6 +143,7 @@ module Mongo
# Connection pools for each secondary node # Connection pools for each secondary node
@secondary_pools = [] @secondary_pools = []
@read_pool = nil
# Maps sockets to pools for checkin # Maps sockets to pools for checkin
@pool_map = {} @pool_map = {}
@ -494,6 +495,8 @@ module Mongo
end end
end end
pick_secondary_for_read
raise ConnectionFailure, "failed to connect to any given host:port" unless connected? raise ConnectionFailure, "failed to connect to any given host:port" unless connected?
end end
@ -512,6 +515,7 @@ module Mongo
def close def close
@primary_pool.close if @primary_pool @primary_pool.close if @primary_pool
@primary_pool = nil @primary_pool = nil
@read_pool = nil
@secondary_pools.each do |pool| @secondary_pools.each do |pool|
pool.close pool.close
end end
@ -595,15 +599,10 @@ module Mongo
def checkout_reader def checkout_reader
connect unless connected? connect unless connected?
case @secondary_pools.size if @read_pool
when 0 then @read_pool.checkout
checkout_writer else
when 1 then checkout_writer
@secondary_pools[0].checkout
else
@secondary_pools.push(pool = @secondary_pools.shift)
@pool_map[socket = pool.checkout] = pool
socket
end end
end end
@ -616,13 +615,10 @@ module Mongo
# Checkin a socket used for reading. # Checkin a socket used for reading.
def checkin_reader(socket) def checkin_reader(socket)
case @secondary_pools.size if @read_pool
when 0 then @read_pool.checkin(socket)
checkin_writer(socket) else
when 1 then checkin_writer(socket)
@secondary_pools[0].checkin(socket)
else
@pool_map[socket].checkin(socket)
end end
end end
@ -635,6 +631,14 @@ module Mongo
private private
# Pick a node randomly from the set of possibly secondaries.
def pick_secondary_for_read
srand(Time.now.to_i)
if (size = @secondary_pools.size) > 1
@read_pool = @secondary_pools[rand(size)]
end
end
# If a ConnectionFailure is raised, this method will be called # If a ConnectionFailure is raised, this method will be called
# to close the connection and reset connection values. # to close the connection and reset connection values.
def reset_connection def reset_connection