Class: HashRing

Inherits:
Object
  • Object
show all
Defined in:
lib/redis_ext/hash_ring.rb

Constant Summary collapse

POINTS_PER_SERVER =

this is the default in libmemcached

160

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nodes = [], replicas = POINTS_PER_SERVER) ⇒ HashRing

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.



12
13
14
15
16
17
18
19
20
# File 'lib/redis_ext/hash_ring.rb', line 12

def initialize(nodes=[], replicas=POINTS_PER_SERVER)
  @replicas = replicas
  @ring = {}
  @nodes = []
  @sorted_keys = []
  nodes.each do |node|
    add_node(node)
  end
end

Instance Attribute Details

#nodesObject (readonly)

Returns the value of attribute nodes.



7
8
9
# File 'lib/redis_ext/hash_ring.rb', line 7

def nodes
  @nodes
end

#replicasObject (readonly)

Returns the value of attribute replicas.



7
8
9
# File 'lib/redis_ext/hash_ring.rb', line 7

def replicas
  @replicas
end

#ringObject (readonly)

Returns the value of attribute ring.



7
8
9
# File 'lib/redis_ext/hash_ring.rb', line 7

def ring
  @ring
end

#sorted_keysObject (readonly)

Returns the value of attribute sorted_keys.



7
8
9
# File 'lib/redis_ext/hash_ring.rb', line 7

def sorted_keys
  @sorted_keys
end

Instance Method Details

#add_node(node) ⇒ Object

Adds a ‘node` to the hash ring (including a number of replicas).



23
24
25
26
27
28
29
30
31
# File 'lib/redis_ext/hash_ring.rb', line 23

def add_node(node)
  @nodes << node
  @replicas.times do |i|
    key = Zlib.crc32("#{node}:#{i}")
    @ring[key] = node
    @sorted_keys << key
  end
  @sorted_keys.sort!
end

#get_node(key) ⇒ Object

get the node in the hash ring for this key



43
44
45
# File 'lib/redis_ext/hash_ring.rb', line 43

def get_node(key)
  get_node_pos(key)[0]
end

#get_node_pos(key) ⇒ Object



47
48
49
50
51
52
# File 'lib/redis_ext/hash_ring.rb', line 47

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

#iter_nodes(key) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/redis_ext/hash_ring.rb', line 54

def iter_nodes(key)
  return [nil,nil] if @ring.size == 0
  node, pos = get_node_pos(key)
  @sorted_keys[pos..-1].each do |k|
    yield @ring[k]
  end  
end

#remove_node(node) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/redis_ext/hash_ring.rb', line 33

def remove_node(node)
  @nodes.reject!{|n| n.to_s == node.to_s}
  @replicas.times do |i|
    key = Zlib.crc32("#{node}:#{i}")
    @ring.delete(key)
    @sorted_keys.reject! {|k| k == key}
  end
end