Memcached - Set Data
Memcached - Storing Data with Set
Section titled “Memcached - Storing Data with Set”The Memcached set command is the most fundamental and widely used write operation. It stores a key-value pair in the cache. If the key already exists, set will unconditionally overwrite its current value and expiration time.
Protocol Syntax
Section titled “Protocol Syntax”When interacting with Memcached directly (e.g., via telnet), the syntax is:
set key flags exptime bytes [noreply]valuekey: The name of the key to store the data under.flags: A 32-bit integer that is stored with the value and returned on retrieval. Client libraries often use this for serialization metadata (e.g., distinguishing between strings, numbers, and pickled objects).exptime: The expiration time in seconds. A value of0means the item never expires. If the value is over 30 days (2592000), it’s treated as a Unix timestamp of the absolute expiration time.bytes: The length of thevaluein bytes.noreply(optional): Instructs the server not to send a response, reducing latency.value: The data to be stored, sent on a new line.
Expected Responses
Section titled “Expected Responses”STOREDindicates the data was successfully stored.ERRORindicates a syntax error or other issue during storage.
Telnet Example
Section titled “Telnet Example”This example demonstrates setting a key, verifying it, and then overwriting it with a new value.
# 1. Set a key 'website:title' with a 15-minute (900s) expiration.set website:title 0 900 23World's Largest LibrarySTORED
# 2. Retrieve the value to confirm.get website:titleVALUE website:title 0 23World's Largest LibraryEND
# 3. Set the same key again with a new value. This overwrites the old one.set website:title 0 900 25Modern Tech TutorialsSTORED
# 4. Verify the new value is in place.get website:titleVALUE website:title 0 25Modern Tech TutorialsENDModern Application: Storing Data with Python
Section titled “Modern Application: Storing Data with Python”In a modern application, you’ll use a client library. Here’s how to use set with Python and pymemcache, including how to handle different data types.
Setup and Dependencies
Section titled “Setup and Dependencies”First, install the library using pip:
pip install pymemcachePython Code Example with Serialization
Section titled “Python Code Example with Serialization”import jsonfrom pymemcache.client.base import Clientfrom pymemcache.serde import Serde
MEMCACHED_SERVER = ('127.0.0.1', 11211)
# Best Practice: Use a serializer for non-string data.# This ensures data is stored and retrieved consistently.json_serde = Serde( serializer=lambda k, v: (json.dumps(v).encode('utf-8'), 1), deserializer=lambda k, v, f: json.loads(v.decode('utf-8')) if f == 1 else v)
def run_set_example(): """Demonstrates setting various data types in Memcached.""" # Pass the serializer to the client on initialization client = Client(MEMCACHED_SERVER, serde=json_serde)
try: # --- Example 1: Storing a simple string --- key1 = 'api:status_message' value1 = 'Service is running normally.' client.set(key1, value1, expire=300) retrieved1 = client.get(key1) print(f"Set and got string: '{retrieved1}'")
# --- Example 2: Storing a dictionary (using JSON serde) --- key2 = 'user:profile:42' value2 = { 'username': 'jane_doe', 'email': 'jane.doe@example.com', 'roles': ['editor', 'commenter'], 'last_login_ts': 1672531200 } client.set(key2, value2, expire=3600) retrieved2 = client.get(key2) print(f"Set and got dictionary: {retrieved2}") print(f"Type of retrieved object: {type(retrieved2)}")
except Exception as e: print(f"An unexpected error occurred: {e}") finally: client.close() print("Connection closed.")
if __name__ == "__main__": run_set_example()Expected Output
Section titled “Expected Output”Set and got string: 'Service is running normally.'Set and got dictionary: {'username': 'jane_doe', 'email': 'jane.doe@example.com', 'roles': ['editor', 'commenter'], 'last_login_ts': 1672531200}Type of retrieved object: <class 'dict'>Connection closed.Best Practices and Real-World Applications
Section titled “Best Practices and Real-World Applications”- Primary Caching Strategy:
setis the workhorse of caching. The most common use case is caching the result of an expensive database query or an API call. A web application would first try togetthe data from Memcached. On a cache miss, it fetches from the database and then usessetto store the result in the cache for subsequent requests. - Choose a TTL Wisely: Setting an appropriate Time-To-Live (
expire) is crucial. For data that changes infrequently, a long TTL is fine. For rapidly changing data, a short TTL (e.g., 60 seconds) is better to reduce staleness. Never-expiring keys (expire=0) should be used with caution as they can fill up the cache. - Serialization: Always use a consistent serialization method (like JSON) for complex data types. This ensures that what you
setis what youget, regardless of the client library or programming language used to access the cache. setvs.addvs.replace: Remember the difference:setalways works (create or update).addonly works if the key does not exist.replaceonly works if the key already exists.