The interface to memcached supports the following methods for storing and retrieving information in the cache, and these are consistent across all the different APIs, although the language specific mechanics might be different:
get(
: Retrieves information from the cache. Returns the value associated with the key if the specified key exists. Returnskey
)NULL
,nil
,undefined
, or the closest equivalent in the corresponding language, if the specified key does not exist.set(
: Sets the item associated with a key in the cache to the specified value. This either updates an existing item if the key already exists, or adds a new key-value pair if the key doesn't exist. If the expiry time is specified, then the item expires (and is deleted) when the expiry time is reached. The time is specified in seconds, and is taken as a relative time if the value is less than 30 days (30*24*60*60), or an absolute time (epoch) if larger than this value.key
,value
[,expiry
])add(
: Adds the key and associated value to the cache, if the specified key does not already exist.key
,value
[,expiry
])replace(
: Replaces the item associated with the specifiedkey
,value
[,expiry
])key
, only if the key already exists. The new value is given by thevalue
parameter.delete(
: Deletes thekey
[,time
])key
and its associated item from the cache. If you supply atime
, then adding another item with the specifiedkey
is blocked for the specified period.incr(
: Increments the item associated with thekey
,value
)key
by the specifiedvalue
.decr(
: Decrements the item associated with thekey
,value
)key
by the specifiedvalue
.flush_all
: Invalidates (or expires) all the current items in the cache. Technically they still exist (they are not deleted), but they are silently destroyed the next time you try to access them.
In all implementations, most or all of these functions are duplicated through the corresponding native language interface.
When practical, use memcached to store full items, rather than caching a single column value from the database. For example, when displaying a record about an object (invoice, user history, or blog post), load all the data for the associated entry from the database, and compile it into the internal structure that would normally be required by the application. Save the complete object in the cache.
Complex data structures cannot be stored directly. Most
interfaces serialize the data for you, that is, put it in a
textual form that can reconstruct the original pointers and
nesting. Perl uses Storable
, PHP uses
serialize
, Python uses
cPickle
(or Pickle
) and
Java uses the Serializable
interface. In most
cases, the serialization interface used is customizable. To
share data stored in memcached instances
between different language interfaces, consider using a common
serialization solution such as JSON (Javascript Object
Notation).