Class: MemCache

Class | MemCache
In: | lib/active_support/vendor/memcache-client-1.7.4/memcache.rb
Parent: | Object

A Ruby client library for memcached.

### Methods

[] []= active? add append cache_decr cache_get cache_get_multi cache_incr cas check_multithread_status! create_continuum_for decr delete entry_count_for fetch flush_all get get_multi get_server_for_key gets handle_error hash_for incr inspect make_cache_key new noreply prepend raise_on_error_response! readonly? replace request_setup reset servers= set stats with_server with_socket_management

### Classes and Modules

Class MemCache::MemCacheError
Class MemCache::Server

### Constants

VERSION | = | '1.7.4' |  | The version of MemCache you are using.
DEFAULT_OPTIONS | = | { :namespace => nil, :readonly => false, :multithread => true, :failover => true, :timeout => 0.5, :logger => nil, :no_reply => false, } |  | Default options for the cache object.
DEFAULT_PORT | = | 11211 |  | Default memcached port.
DEFAULT_WEIGHT | = | 1 |  | Default memcached server weight.
ONE_MB | = | 1024 * 1024 |  | Add `key` to the cache with value `value` that expires in `expiry` seconds. If `raw` is true, `value` will not be Marshalled. Warning: Readers should not call this method in the event of a cache miss; see MemCache#add.

### Attributes

failover | [R] | Should the client try to failover to another server if the first server is down? Defaults to true.
logger | [R] | Log debug/info/warn/error to the given Logger, defaults to nil.
multithread | [R] | The multithread setting for this instance
namespace | [R] | The namespace for this instance
no_reply | [R] | Don‘t send or look for a reply from the memcached server for write operations. Please note this feature only works in memcached 1.2.5 and later. Earlier versions will reply with "ERROR".
servers | [R] | The servers this client talks to. Play at your own peril.
timeout | [R] | Socket timeout limit with this client, defaults to 0.5 sec. Set to nil to disable timeouts.

### Public Class methods

new(*args)

Accepts a list of `servers` and a list of `opts`. `servers` may be omitted. See +servers=+ for acceptable server list arguments.

Valid options for `opts` are:

      [:namespace]   Prepends this value to all keys added or retrieved.
      [:readonly]    Raises an exception on cache writes when true.
      [:multithread] Wraps cache access in a Mutex for thread safety. Defaults to true.
      [:failover]    Should the client try to failover to another server if the
                     first server is down?  Defaults to true.
      [:timeout]     Time to use as the socket read timeout.  Defaults to 0.5 sec,
                     set to nil to disable timeouts (this is a major performance penalty in Ruby 1.8,
                     "gem install SystemTimer' to remove most of the penalty).
      [:logger]      Logger to use for info/debug output, defaults to nil
      [:no_reply]    Don't bother looking for a reply for write operations (i.e. they
                     become 'fire and forget'), memcached 1.2.5 and later only, speeds up
                     set/add/delete/incr/decr significantly.

Other options are ignored.

### Public Instance methods

[](key, raw = false)

Alias for get

[]=(key, value)

Shortcut to save a value in the cache. This method does not set an expiration on the entry. Use set to specify an explicit expiry.

active?()

Returns whether there is at least one active server for the object.

add(key, value, expiry = 0, raw = false)

Add `key` to the cache with value `value` that expires in `expiry` seconds, but only if `key` does not already exist in the cache. If `raw` is true, `value` will not be Marshalled.

Readers should call this method in the event of a cache miss, not MemCache#set.

append(key, value)

Append - ‘add this data to an existing key after existing data’ Please note the value is always passed to memcached as raw since it doesn‘t make a lot of sense to concatenate marshalled data together.

cas(key, expiry=0, raw=false) {|value| ...}

"cas" is a check and set operation which means "store this data but only if no one else has updated since I last fetched it." This can be used as a form of optimistic locking.

Works in block form like so:

      cache.cas('some-key') do |value|
        value + 1
      end

Returns: `nil` if the value was not found on the memcached server. `STORED` if the value was updated successfully `EXISTS` if the value was updated by someone else since last fetch

decr(key, amount = 1)

Decrements the value for `key` by `amount` and returns the new value. `key` must already exist. If `key` is not an integer, it is assumed to be

1. `key` can not be decremented below 0.

delete(key, expiry = 0)

Removes `key` from the cache in `expiry` seconds.

fetch(key, expiry = 0, raw = false) {|| ...}

Performs a `get` with the given `key`. If the value does not exist and a block was given, the block will be called and the result saved via `add`.

If you do not provide a block, using this method is the same as using `get`.

flush_all(delay=0)

Flush the cache from all memcache servers. A non-zero value for `delay` will ensure that the flush is propogated slowly through your memcached server farm. The Nth server will be flushed N*delay seconds from now, asynchronously so this method returns quickly. This prevents a huge database spike due to a total flush all at once.

get(key, raw = false)

Retrieves `key` from memcache. If `raw` is false, the value will be unmarshalled.

get_multi(*keys)

Retrieves multiple values from memcached in parallel, if possible.

The memcached protocol supports the ability to retrieve multiple keys in a single request. Pass in an array of keys to this method and it will:

1. map the key to the appropriate memcached server
2. send a single request to each server that has one or more key values

Returns a hash of values.

      cache["a"] = 1
      cache["b"] = 2
      cache.get_multi "a", "b" # => { "a" => 1, "b" => 2 }

Note that get_multi assumes the values are marshalled.

incr(key, amount = 1)

Increments the value for `key` by `amount` and returns the new value. `key` must already exist. If `key` is not an integer, it is assumed to be 0.

inspect()

Returns a string representation of the cache object.

prepend(key, value)

Prepend - ‘add this data to an existing key before existing data’ Please note the value is always passed to memcached as raw since it doesn‘t make a lot of sense to concatenate marshalled data together.

readonly?()

Returns whether or not the cache object was created read only.

replace(key, value, expiry = 0, raw = false)

Add `key` to the cache with value `value` that expires in `expiry` seconds, but only if `key` already exists in the cache. If `raw` is true, `value` will not be Marshalled.

reset()

Reset the connection to all memcache servers. This should be called if there is a problem with a cache lookup that might have left the connection in a corrupted state.

servers=(servers)

Set the servers that the requests will be distributed between. Entries can be either strings of the form "hostname:port" or "hostname:port:weight" or MemCache::Server objects.

set(key, value, expiry = 0, raw = false)
stats()

Returns statistics for each memcached server. An explanation of the statistics can be found in the memcached docs:

code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

Example:

      >> pp CACHE.stats
      {"localhost:11211"=>
        {"bytes"=>4718,
         "pid"=>20188,
         "connection_structures"=>4,
         "time"=>1162278121,
         "pointer_size"=>32,
         "limit_maxbytes"=>67108864,
         "cmd_get"=>14532,
         "version"=>"1.2.0",
         "bytes_written"=>432583,
         "cmd_set"=>32,
         "get_misses"=>0,
         "total_connections"=>19,
         "curr_connections"=>3,
         "curr_items"=>4,
         "uptime"=>1557,
         "get_hits"=>14532,
         "total_items"=>32,
         "rusage_system"=>0.313952,
         "rusage_user"=>0.119981,
         "bytes_read"=>190619}}
      => nil

### Protected Instance methods

cache_decr(server, cache_key, amount)

Performs a raw decr for `cache_key` from `server`. Returns nil if not found.

cache_get(server, cache_key)

Fetches the raw data for `cache_key` from `server`. Returns nil on cache miss.

cache_get_multi(server, cache_keys)

Fetches `cache_keys` from `server` using a multi-get.

cache_incr(server, cache_key, amount)

Performs a raw incr for `cache_key` from `server`. Returns nil if not found.

check_multithread_status!()
create_continuum_for(servers)
entry_count_for(server, total_servers, total_weight)
get_server_for_key(key, options = {})

Pick a server to handle the request based on a hash of the key.

gets(key, raw = false)
handle_error(server, error)

Handles `error` from `server`.

hash_for(key)

Returns an interoperable hash value for `key`. (I think, docs are sketchy for down servers).

make_cache_key(key)

Create a key for the cache, incorporating the namespace qualifier if requested.

noreply()
raise_on_error_response!(response)
request_setup(key)

Performs setup for making a request with `key` from memcached. Returns the server to fetch the key from and the complete key to use.

with_server(key) {|server, cache_key| ...}
with_socket_management(server, &block)

Gets or creates a socket connected to the given server, and yields it to the block, wrapped in a mutex synchronization if @multithread is true.

If a socket error (SocketError, SystemCallError, IOError) or protocol error (MemCacheError) is raised by the block, closes the socket, attempts to connect again, and retries the block (once). If an error is again raised, reraises it as MemCacheError.

If unable to connect to the server (or if in the reconnect wait period), raises MemCacheError. Note that the socket connect code marks a server dead for a timeout period, so retrying does not apply to connection attempt failures (but does still apply to unexpectedly lost connections etc.).

[Validate]