Class: Dalli::Ring

Inherits:
Object
  • Object
show all
Defined in:
lib/dalli/ring.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

POINTS_PER_SERVER =

this is the default in libmemcached

160

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(servers, options) ⇒ Ring

Returns a new instance of Ring.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/dalli/ring.rb', line 11

def initialize(servers, options)
  @servers = servers
  @continuum = nil
  if servers.size > 1
    total_weight = servers.inject(0) { |memo, srv| memo + srv.weight }
    continuum = []
    servers.each do |server|
      entry_count_for(server, servers.size, total_weight).times do |idx|
        hash = Digest::SHA1.hexdigest("#{server.name}:#{idx}")
        value = Integer("0x#{hash[0..7]}")
        continuum << Dalli::Ring::Entry.new(value, server)
      end
    end
    @continuum = continuum.sort_by(&:value)
  end

  threadsafe! unless options[:threadsafe] == false
  @failover = options[:failover] != false
end

Instance Attribute Details

#continuumObject

Returns the value of attribute continuum.



9
10
11
# File 'lib/dalli/ring.rb', line 9

def continuum
  @continuum
end

#serversObject

Returns the value of attribute servers.



9
10
11
# File 'lib/dalli/ring.rb', line 9

def servers
  @servers
end

Instance Method Details

#lockObject



49
50
51
52
53
54
55
56
# File 'lib/dalli/ring.rb', line 49

def lock
  @servers.each(&:lock!)
  begin
    return yield
  ensure
    @servers.each(&:unlock!)
  end
end

#server_for_key(key) ⇒ Object

Raises:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dalli/ring.rb', line 31

def server_for_key(key)
  if @continuum
    hkey = hash_for(key)
    20.times do |try|
      entryidx = binary_search(@continuum, hkey)
      server = @continuum[entryidx].server
      return server if server.alive?
      break unless @failover
      hkey = hash_for("#{try}#{key}")
    end
  else
    server = @servers.first
    return server if server && server.alive?
  end

  raise Dalli::RingError, "No server available"
end