Class: LoadBalancer::WeightRoundRobin

Inherits:
Algo
  • Object
show all
Defined in:
lib/multi_dbs_load_balancer/load_balancer/weight_round_robin.rb

Instance Attribute Summary

Attributes inherited from Algo

#database_configs, #key, #redis

Instance Method Summary collapse

Methods inherited from Algo

#after_connected, #after_executed, #connected_to_next_db, #fail_over, #initialize

Methods included from Healthcheck

#db_available?, #mark_db_down, #mark_redis_down, #redis_available?

Methods included from RedisLua

eval_lua_script

Constructor Details

This class inherits a constructor from LoadBalancer::Algo

Instance Method Details

#next_db(**options) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/multi_dbs_load_balancer/load_balancer/weight_round_robin.rb', line 21

def next_db(**options)
    db_index = pick_db_by_random_weight
    return @database_configs[db_index], db_index if db_available?(db_index)
    
    # fail over
    next_dbs = (db_index+1...db_index+@database_configs.size).map { |i| i % @database_configs.size }
    fail_over(next_dbs)
end

#warm_upObject



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/multi_dbs_load_balancer/load_balancer/weight_round_robin.rb', line 9

def warm_up
    (@@mutexes[weights_key] ||= Mutex.new).synchronize do
        return if @@cum_weights.has_key?(weights_key) or @database_configs.empty?

        @@cum_weights[weights_key] = [@database_configs[0][:weight]]
        (1...@database_configs.size).each do |i|
            @@weight_sums[weight_sum_key] += @database_configs[i][:weight]
            @@cum_weights[weights_key][i] = @@cum_weights[weights_key][i-1] + @database_configs[i][:weight]
        end
    end
end