2.12. Memcached

Memcached is a distributed memory caching system for uninterpreted arrays of bytes.

Architecture

  • clients access data

    • data as key value pairs

    • key is a string (250 B limit)

    • value is array of bytes (1 MB limit)

    • client side compression supported

  • servers cache data

    • standardized protocols

      • can use TCP or UDP

      • transparent binary protocol

      • text protocol limits keys and values

  • servers do not know each other

  • server selected by client side hashing

  • least recently used strategy for eviction

Usage Example

// Initialization of memcache client.
mem = new Memcache ()
mem.add_server ("10.0.0.1:12345")
mem.add_server ("10.0.0.2:12345")
mem.add_server ("10.0.0.3:12345")
// Construct key for database query.
sql = "SELECT * FROM user WHERE name = ?"
key = "SQL:" + hash (sql) + name

// Try to fetch value from memcache.
if (defined (result = mem.get (key))) return (result)

// Fetch value from database and populate memcache otherwise.
result = execute_query (sql, name)
mem.set (key, result, lifetime)
return (result)
// Example adjusted from documentation, see references.
  • getting and setting values of keys

  • atomic setting of values for new keys

  • incrementing and decrementing of integer values

  • invalidating values by keys

2.12.1. References

  1. The Memcached Website. http://www.memcached.org