Parent

Dalli::Client

Public Class Methods

new(servers=nil, options={}) click to toggle source

Dalli::Client is the main class which developers will use to interact with the memcached server. Usage:

Dalli::Client.new(['localhost:11211:10', 'cache-2.example.com:11211:5', '192.168.0.1:22122:5'],
                :threadsafe => true, :failover => true, :expires_in => 300)

servers is an Array of "host:port:weight" where weight allows you to distribute cache unevenly. Both weight and port are optional. If you pass in nil, Dalli will use the MEMCACHE_SERVERS environment variable or default to 'localhost:11211' if it is not present.

Options:

  • :namespace - prepend each key with this value to provide simple namespacing.

  • :failover - if a server is down, look for and store values on another server in the ring. Default: true.

  • :threadsafe - ensure that only one thread is actively using a socket at a time. Default: true.

  • :expires_in - default TTL in seconds if you do not pass TTL as a parameter to an individual operation, defaults to 0 or forever

  • :compress - defaults to false, if true Dalli will compress values larger than 1024 bytes before

  • :serializer - defaults to Marshal sending them to memcached.

  • :compressor - defaults to zlib

# File lib/dalli/client.rb, line 29
def initialize(servers=nil, options={})
  @servers = servers || env_servers || '127.0.0.1:11211'
  @options = normalize_options(options)
  @ring = nil
end

Public Instance Methods

add(key, value, ttl=nil, options=nil) click to toggle source

Conditionally add a key/value pair, if the key does not already exist on the server. Returns true if the operation succeeded.

# File lib/dalli/client.rb, line 179
def add(key, value, ttl=nil, options=nil)
  ttl ||= @options[:expires_in].to_i
  perform(:add, key, value, ttl, options)
end
append(key, value) click to toggle source

Append value to the value already stored on the server for 'key'. Appending only works for values stored with :raw => true.

# File lib/dalli/client.rb, line 199
def append(key, value)
  perform(:append, key, value.to_s)
end
cas(key, ttl=nil, options=nil, &block) click to toggle source

compare and swap values using optimistic locking. Fetch the existing value for key. If it exists, yield the value to the block. Add the block's return value as the new value for the key. Add will fail if someone else changed the value.

Returns:

  • nil if the key did not exist.

  • false if the value was changed by someone else.

  • true if the value was successfully updated.

# File lib/dalli/client.rb, line 161
def cas(key, ttl=nil, options=nil, &block)
  ttl ||= @options[:expires_in].to_i
  (value, cas) = perform(:cas, key)
  value = (!value || value == 'Not found') ? nil : value
  if value
    newvalue = block.call(value)
    perform(:set, key, newvalue, ttl, cas, options)
  end
end
close() click to toggle source

Close our connection to each server. If you perform another operation after this, the connections will be re-established.

# File lib/dalli/client.rb, line 286
def close
  if @ring
    @ring.servers.each { |s| s.close }
    @ring = nil
  end
end
Also aliased as: reset
decr(key, amt=1, ttl=nil, default=nil) click to toggle source

Decr subtracts the given amount from the counter on the memcached server. Amt must be a positive integer value.

memcached counters are unsigned and cannot hold negative values. Calling decr on a counter which is 0 will just return 0.

If default is nil, the counter must already exist or the operation will fail and will return nil. Otherwise this method will return the new value for the counter.

Note that the ttl will only apply if the counter does not already exist. To decrease an existing counter and update its TTL, use cas.

# File lib/dalli/client.rb, line 248
def decr(key, amt=1, ttl=nil, default=nil)
  raise ArgumentError, "Positive values only: #{amt}" if amt < 0
  ttl ||= @options[:expires_in].to_i
  perform(:decr, key, amt.to_i, ttl, default)
end
delete(key) click to toggle source
# File lib/dalli/client.rb, line 192
def delete(key)
  perform(:delete, key)
end
fetch(key, ttl=nil, options=nil) click to toggle source
# File lib/dalli/client.rb, line 140
def fetch(key, ttl=nil, options=nil)
  ttl ||= @options[:expires_in].to_i
  val = get(key, options)
  if val.nil? && block_given?
    val = yield
    add(key, val, ttl, options)
  end
  val
end
flush(delay=0) click to toggle source
# File lib/dalli/client.rb, line 210
def flush(delay=0)
  time = -delay
  ring.servers.map { |s| s.request(:flush, time += delay) }
end
Also aliased as: flush_all
flush_all(delay=0) click to toggle source
Alias for: flush
get(key, options=nil) click to toggle source
# File lib/dalli/client.rb, line 51
def get(key, options=nil)
  resp = perform(:get, key)
  resp.nil? || resp == 'Not found' ? nil : resp
end
get_multi(*keys) click to toggle source

Fetch multiple keys efficiently. Returns a hash of { 'key' => 'value', 'key2' => 'value1' }

# File lib/dalli/client.rb, line 59
def get_multi(*keys)
  return {} if keys.empty?
  options = nil
  options = keys.pop if keys.last.is_a?(Hash) || keys.last.nil?
  ring.lock do
    begin
      servers = self.servers_in_use = Set.new

      keys.flatten.each do |key|
        begin
          perform(:getkq, key)
        rescue DalliError, NetworkError => e
          Dalli.logger.debug { e.inspect }
          Dalli.logger.debug { "unable to get key #{key}" }
        end
      end

      values = {}
      return values if servers.empty?

      servers.each do |server|
        next unless server.alive?
        begin
          server.multi_response_start
        rescue DalliError, NetworkError => e
          Dalli.logger.debug { e.inspect }
          Dalli.logger.debug { "results from this server will be missing" }
          servers.delete(server)
        end
      end

      start = Time.now
      loop do
        # remove any dead servers
        servers.delete_if { |s| s.sock.nil? }
        break if servers.empty?

        # calculate remaining timeout
        elapsed = Time.now - start
        timeout = servers.first.options[:socket_timeout]
        if elapsed > timeout
          readable = nil
        else
          sockets = servers.map(&:sock)
          readable, _ = IO.select(sockets, nil, nil, timeout - elapsed)
        end

        if readable.nil?
          # no response within timeout; abort pending connections
          servers.each do |server|
            puts "Abort!"
            server.multi_response_abort
          end
          break

        else
          readable.each do |sock|
            server = sock.server

            begin
              server.multi_response_nonblock.each do |key, value|
                values[key_without_namespace(key)] = value
              end

              if server.multi_response_completed?
                servers.delete(server)
              end
            rescue NetworkError
              servers.delete(server)
            end
          end
        end
      end

      values
    ensure
      self.servers_in_use = nil
    end
  end
end
incr(key, amt=1, ttl=nil, default=nil) click to toggle source

Incr adds the given amount to the counter on the memcached server. Amt must be a positive integer value.

If default is nil, the counter must already exist or the operation will fail and will return nil. Otherwise this method will return the new value for the counter.

Note that the ttl will only apply if the counter does not already exist. To increase an existing counter and update its TTL, use cas.

# File lib/dalli/client.rb, line 228
def incr(key, amt=1, ttl=nil, default=nil)
  raise ArgumentError, "Positive values only: #{amt}" if amt < 0
  ttl ||= @options[:expires_in].to_i
  perform(:incr, key, amt.to_i, ttl, default)
end
multi() click to toggle source

Turn on quiet aka noreply support. All relevant operations within this block will be effectively pipelined as Dalli will use 'quiet' operations where possible. Currently supports the set, add, replace and delete operations.

# File lib/dalli/client.rb, line 44
def multi
  old, Thread.current[:dalli_multi] = Thread.current[:dalli_multi], true
  yield
ensure
  Thread.current[:dalli_multi] = old
end
prepend(key, value) click to toggle source

Prepend value to the value already stored on the server for 'key'. Prepending only works for values stored with :raw => true.

# File lib/dalli/client.rb, line 206
def prepend(key, value)
  perform(:prepend, key, value.to_s)
end
replace(key, value, ttl=nil, options=nil) click to toggle source

Conditionally add a key/value pair, only if the key already exists on the server. Returns true if the operation succeeded.

# File lib/dalli/client.rb, line 187
def replace(key, value, ttl=nil, options=nil)
  ttl ||= @options[:expires_in].to_i
  perform(:replace, key, value, ttl, options)
end
reset() click to toggle source
Alias for: close
reset_stats() click to toggle source

Reset stats for each server.

# File lib/dalli/client.rb, line 277
def reset_stats
  ring.servers.map do |server|
    server.alive? ? server.request(:reset_stats) : nil
  end
end
set(key, value, ttl=nil, options=nil) click to toggle source
# File lib/dalli/client.rb, line 171
def set(key, value, ttl=nil, options=nil)
  ttl ||= @options[:expires_in].to_i
  perform(:set, key, value, ttl, 0, options)
end
stats() click to toggle source

Collect the stats for each server. Returns a hash like { 'hostname:port' => { 'stat1' => 'value1', ... }, 'hostname2:port' => { ... } }

# File lib/dalli/client.rb, line 267
def stats
  values = {}
  ring.servers.each do |server|
    values["#{server.hostname}:#{server.port}"] = server.alive? ? server.request(:stats) : nil
  end
  values
end
touch(key, ttl=nil) click to toggle source

Touch updates expiration time for a given key.

Returns true if key exists, otherwise nil.

# File lib/dalli/client.rb, line 258
def touch(key, ttl=nil)
  ttl ||= @options[:expires_in].to_i
  resp = perform(:touch, key, ttl)
  resp.nil? ? nil : true
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.