Class: Dalli::Client

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

Overview

Dalli::Client is the main class which developers will use to interact with Memcached.

Constant Summary collapse

CACHE_NILS =
{ cache_nils: true }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(servers = nil, options = {}) ⇒ Client

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',
                   '/var/run/memcached/socket'],
                  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. Dalli also supports the ability to connect to Memcached on localhost through a UNIX socket. To use this functionality, use a full pathname (beginning with a slash character '/') in place of the “host:port” pair in the server configuration.

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 - if true Dalli will compress values larger than compression_min_size bytes before sending them

    to memcached.  Default: true.
    
  • :compression_min_size - the minimum size (in bytes) for which Dalli will compress values sent to Memcached.

    Defaults to 4K.
    
  • :serializer - defaults to Marshal

  • :compressor - defaults to Dalli::Compressor, a Zlib-based implementation

  • :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for

    #fetch operations.
    
  • :digest_class - defaults to Digest::MD5, allows you to pass in an object that responds to the hexdigest method,

    useful for injecting a FIPS compliant hash object.
    
  • :protocol_implementation - defaults to Dalli::Protocol::Binary which uses the binary protocol. Allows you to

    pass an alternative implementation using another protocol.
    

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

def initialize(servers = nil, options = {})
  @servers = ::Dalli::ServersArgNormalizer.normalize_servers(servers)
  @options = normalize_options(options)
  @key_manager = ::Dalli::KeyManager.new(options)
  @ring = nil
end

Instance Method Details

#add(key, value, ttl = nil, options = nil) ⇒ Object

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


160
161
162
# File 'lib/dalli/client.rb', line 160

def add(key, value, ttl = nil, options = nil)
  perform(:add, key, value, ttl_or_default(ttl), options)
end

#alive!Object

Make sure memcache servers are alive, or raise an Dalli::RingError


273
274
275
# File 'lib/dalli/client.rb', line 273

def alive!
  ring.server_for_key('')
end

#append(key, value) ⇒ Object

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


178
179
180
# File 'lib/dalli/client.rb', line 178

def append(key, value)
  perform(:append, key, value.to_s)
end

#cache_nilsObject


123
124
125
# File 'lib/dalli/client.rb', line 123

def cache_nils
  @options[:cache_nils]
end

#cas(key, ttl = nil, options = nil, &block) ⇒ Object

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.


138
139
140
# File 'lib/dalli/client.rb', line 138

def cas(key, ttl = nil, options = nil, &block)
  cas_core(key, false, ttl, options, &block)
end

#cas!(key, ttl = nil, options = nil, &block) ⇒ Object

like #cas, but will yield to the block whether or not the value already exists.

Returns:

  • false if the value was changed by someone else.

  • true if the value was successfully updated.


149
150
151
# File 'lib/dalli/client.rb', line 149

def cas!(key, ttl = nil, options = nil, &block)
  cas_core(key, true, ttl, options, &block)
end

#closeObject Also known as: reset

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


342
343
344
345
346
347
# File 'lib/dalli/client.rb', line 342

def close
  return unless @ring

  @ring.servers.each(&:close)
  @ring = nil
end

#decr(key, amt = 1, ttl = nil, default = nil) ⇒ Object

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.

Raises:

  • (ArgumentError)

227
228
229
230
231
# File 'lib/dalli/client.rb', line 227

def decr(key, amt = 1, ttl = nil, default = nil)
  raise ArgumentError, "Positive values only: #{amt}" if amt.negative?

  perform(:decr, key, amt.to_i, ttl_or_default(ttl), default)
end

#delete(key) ⇒ Object


171
172
173
# File 'lib/dalli/client.rb', line 171

def delete(key)
  perform(:delete, key, 0)
end

#delete_cas(key, cas = 0) ⇒ Object

Delete a key/value pair, verifying existing CAS. Returns true if succeeded, and falsy otherwise.


335
336
337
# File 'lib/dalli/client.rb', line 335

def delete_cas(key, cas = 0)
  perform(:delete, key, cas)
end

#fetch(key, ttl = nil, req_options = nil) ⇒ Object

Fetch the value associated with the key. If a value is found, then it is returned.

If a value is not found and no block is given, then nil is returned.

If a value is not found (or if the found value is nil and :cache_nils is false) and a block is given, the block will be invoked and its return value written to the cache and returned.


109
110
111
112
113
114
115
116
117
# File 'lib/dalli/client.rb', line 109

def fetch(key, ttl = nil, req_options = nil)
  req_options = req_options.nil? ? CACHE_NILS : req_options.merge(CACHE_NILS) if cache_nils
  val = get(key, req_options)
  if not_found?(val) && block_given?
    val = yield
    add(key, val, ttl_or_default(ttl), req_options)
  end
  val
end

#flush(delay = 0) ⇒ Object Also known as: flush_all


189
190
191
192
# File 'lib/dalli/client.rb', line 189

def flush(delay = 0)
  time = -delay
  ring.servers.map { |s| s.request(:flush, time += delay) }
end

#gat(key, ttl = nil) ⇒ Object

Gat (get and touch) fetch an item and simultaneously update its expiration time.

If a value is not found, then nil is returned.


246
247
248
# File 'lib/dalli/client.rb', line 246

def gat(key, ttl = nil)
  perform(:gat, key, ttl_or_default(ttl))
end

#get(key, options = nil) ⇒ Object

Get the value associated with the key. If a value is not found, then nil is returned.


76
77
78
# File 'lib/dalli/client.rb', line 76

def get(key, options = nil)
  perform(:get, key, options)
end

#get_cas(key) ⇒ Object

Get the value and CAS ID associated with the key. If a block is provided, value and CAS will be passed to the block.


290
291
292
293
294
295
296
297
298
# File 'lib/dalli/client.rb', line 290

def get_cas(key)
  (value, cas) = perform(:cas, key)
  value = nil if !value || value == 'Not found'
  if block_given?
    yield value, cas
  else
    [value, cas]
  end
end

#get_multi(*keys) ⇒ Object

Fetch multiple keys efficiently. If a block is given, yields key/value pairs one at a time. Otherwise returns a hash of { 'key' => 'value', 'key2' => 'value1' }


84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/dalli/client.rb', line 84

def get_multi(*keys)
  keys.flatten!
  keys.compact!

  return {} if keys.empty?

  if block_given?
    get_multi_yielder(keys) { |k, data| yield k, data.first }
  else
    {}.tap do |hash|
      get_multi_yielder(keys) { |k, data| hash[k] = data.first }
    end
  end
end

#get_multi_cas(*keys) ⇒ Object

Fetch multiple keys efficiently, including available metadata such as CAS. If a block is given, yields key/data pairs one a time. Data is an array:

value, cas_id

If no block is given, returns a hash of

{ 'key' => [value, cas_id] }

306
307
308
309
310
311
312
313
314
# File 'lib/dalli/client.rb', line 306

def get_multi_cas(*keys)
  if block_given?
    get_multi_yielder(keys) { |*args| yield(*args) }
  else
    {}.tap do |hash|
      get_multi_yielder(keys) { |k, data| hash[k] = data }
    end
  end
end

#incr(key, amt = 1, ttl = nil, default = nil) ⇒ Object

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.

Raises:

  • (ArgumentError)

207
208
209
210
211
# File 'lib/dalli/client.rb', line 207

def incr(key, amt = 1, ttl = nil, default = nil)
  raise ArgumentError, "Positive values only: #{amt}" if amt.negative?

  perform(:incr, key, amt.to_i, ttl_or_default(ttl), default)
end

#multiObject

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.


65
66
67
68
69
70
71
# File 'lib/dalli/client.rb', line 65

def multi
  old = Thread.current[:dalli_multi]
  Thread.current[:dalli_multi] = true
  yield
ensure
  Thread.current[:dalli_multi] = old
end

#not_found?(val) ⇒ Boolean

Returns:

  • (Boolean)

119
120
121
# File 'lib/dalli/client.rb', line 119

def not_found?(val)
  cache_nils ? val == Dalli::Protocol::NOT_FOUND : val.nil?
end

#prepend(key, value) ⇒ Object

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


185
186
187
# File 'lib/dalli/client.rb', line 185

def prepend(key, value)
  perform(:prepend, key, value.to_s)
end

#replace(key, value, ttl = nil, options = nil) ⇒ Object

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


167
168
169
# File 'lib/dalli/client.rb', line 167

def replace(key, value, ttl = nil, options = nil)
  perform(:replace, key, value, ttl_or_default(ttl), 0, options)
end

#replace_cas(key, value, cas, ttl = nil, options = nil) ⇒ Object

Conditionally add a key/value pair, verifying existing CAS, only if the key already exists on the server. Returns the new CAS value if the operation succeeded, or falsy otherwise.


328
329
330
331
# File 'lib/dalli/client.rb', line 328

def replace_cas(key, value, cas, ttl = nil, options = nil)
  ttl ||= @options[:expires_in].to_i
  perform(:replace, key, value, ttl, cas, options)
end

#reset_statsObject

Reset stats for each server.


265
266
267
268
269
# File 'lib/dalli/client.rb', line 265

def reset_stats
  ring.servers.map do |server|
    server.alive? ? server.request(:reset_stats) : nil
  end
end

#set(key, value, ttl = nil, options = nil) ⇒ Object


153
154
155
# File 'lib/dalli/client.rb', line 153

def set(key, value, ttl = nil, options = nil)
  perform(:set, key, value, ttl_or_default(ttl), 0, options)
end

#set_cas(key, value, cas, ttl = nil, options = nil) ⇒ Object

Set the key-value pair, verifying existing CAS. Returns the resulting CAS value if succeeded, and falsy otherwise.


319
320
321
322
# File 'lib/dalli/client.rb', line 319

def set_cas(key, value, cas, ttl = nil, options = nil)
  ttl ||= @options[:expires_in].to_i
  perform(:set, key, value, ttl, cas, options)
end

#stats(type = nil) ⇒ Object

Collect the stats for each server. You can optionally pass a type including :items, :slabs or :settings to get specific stats Returns a hash like { 'hostname:port' => { 'stat1' => 'value1', … }, 'hostname2:port' => { … } }


254
255
256
257
258
259
260
261
# File 'lib/dalli/client.rb', line 254

def stats(type = nil)
  type = nil unless [nil, :items, :slabs, :settings].include? type
  values = {}
  ring.servers.each do |server|
    values[server.name.to_s] = server.alive? ? server.request(:stats, type.to_s) : nil
  end
  values
end

#touch(key, ttl = nil) ⇒ Object

Touch updates expiration time for a given key.

Returns true if key exists, otherwise nil.


237
238
239
240
# File 'lib/dalli/client.rb', line 237

def touch(key, ttl = nil)
  resp = perform(:touch, key, ttl_or_default(ttl))
  resp.nil? ? nil : true
end

#versionObject

Version of the memcache servers.


279
280
281
282
283
284
285
# File 'lib/dalli/client.rb', line 279

def version
  values = {}
  ring.servers.each do |server|
    values[server.name.to_s] = server.alive? ? server.request(:version) : nil
  end
  values
end

#with {|_self| ... } ⇒ Object

Stub method so a bare Dalli client can pretend to be a connection pool.

Yields:

  • (_self)

Yield Parameters:

  • _self (Dalli::Client)

    the object that the method was called on


351
352
353
# File 'lib/dalli/client.rb', line 351

def with
  yield self
end