Class: Redis::HashRing

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

Constant Summary

POINTS_PER_SERVER =

this is the default in libmemcached

160

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (HashRing) initialize(nodes = [], replicas = POINTS_PER_SERVER)

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.



13
14
15
16
17
18
19
20
21
# 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

Instance Attribute Details

- (Object) nodes (readonly)

Returns the value of attribute nodes



8
9
10
# File 'lib/redis/hash_ring.rb', line 8

def nodes
  @nodes
end

- (Object) replicas (readonly)

Returns the value of attribute replicas



8
9
10
# File 'lib/redis/hash_ring.rb', line 8

def replicas
  @replicas
end

- (Object) ring (readonly)

Returns the value of attribute ring



8
9
10
# File 'lib/redis/hash_ring.rb', line 8

def ring
  @ring
end

- (Object) sorted_keys (readonly)

Returns the value of attribute sorted_keys



8
9
10
# File 'lib/redis/hash_ring.rb', line 8

def sorted_keys
  @sorted_keys
end

Instance Method Details

- (Object) add_node(node)

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



24
25
26
27
28
29
30
31
32
# 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

- (Object) get_node(key)

get the node in the hash ring for this key



44
45
46
# File 'lib/redis/hash_ring.rb', line 44

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

- (Object) get_node_pos(key)



48
49
50
51
52
53
# 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

- (Object) iter_nodes(key)



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

def iter_nodes(key)
  return [nil,nil] if @ring.size == 0
  _, pos = get_node_pos(key)
  @ring.size.times do |n|
    yield @ring[@sorted_keys[(pos+n) % @ring.size]]
  end
end

- (Object) remove_node(node)



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

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