Memcached stores data in the form of key-value pairs, where both keys and values are strings. When a client sends a request to store or retrieve data, it specifies the key string associated with the data.
Memcached uses a hash table to store these key-value pairs. The hash table is divided into a fixed number of buckets, typically 1024 by default, each containing a linked list of key-value pairs. The client's key is hashed, and the resulting value is used to determine which bucket the data should be stored in.
When storing data in Memcached, the client sends the key-value pair to the Memcached server, which hashes the key to determine which bucket the data should be stored in. If the bucket already contains an entry for that key, the new value overwrites the old one. If that bucket does not contain any entry for that key, a new key-value pair is appended to the linked list in the corresponding bucket.
When retrieving data from Memcached, the client sends the key associated with the data it wants to retrieve. The server performs a lookup of the key in the hash table and returns the associated value if it exists. If the key is not found in the hash table, Memcached returns a miss and the client must retrieve the data from its original source.
Here's an example code snippet showing how to set and get values in Memcached using the Python
This code sets the value
'my_value' for the key
'my_key' in Memcached, then retrieves and prints it.