Object
Find the closest index in HashRing with value <= the given value
# File lib/redis/hash_ring.rb, line 103 def binary_search(ary, value, &block) upper = ary.size - 1 lower = 0 idx = 0 while(lower <= upper) do idx = (lower + upper) / 2 comp = ary[idx] <=> value if comp == 0 return idx elsif comp > 0 upper = idx - 1 else lower = idx + 1 end end if upper < 0 upper = ary.size - 1 end return upper end
nodes is a list of objects that have a proper to_s representation. replicas indicates how many virtual points should be used pr. node, replicas are required to improve the distribution.
# File lib/redis/hash_ring.rb, line 13 def initialize(nodes=[], replicas=POINTS_PER_SERVER) @replicas = replicas @ring = {} @nodes = [] @sorted_keys = [] nodes.each do |node| add_node(node) end end
Adds a `node` to the hash ring (including a number of replicas).
# File lib/redis/hash_ring.rb, line 24 def add_node(node) @nodes << node @replicas.times do |i| key = Zlib.crc32("#{node.id}:#{i}") @ring[key] = node @sorted_keys << key end @sorted_keys.sort! end
get the node in the hash ring for this key
# File lib/redis/hash_ring.rb, line 44 def get_node(key) get_node_pos(key)[0] end
# File lib/redis/hash_ring.rb, line 48 def get_node_pos(key) return [nil,nil] if @ring.size == 0 crc = Zlib.crc32(key) idx = HashRing.binary_search(@sorted_keys, crc) return [@ring[@sorted_keys[idx]], idx] end
Generated with the Darkfish Rdoc Generator 2.