Skip to content
Memcached

set / get — Basic Key-Value

Store and retrieve values by key with expiration and flags.

By EZ4Code Team
setgetbasic

Code

# telnet / nc style protocol (text)
set user:42 0 3600 13
hello, world!
# STORED
#    ^ flags=0 ^ ttl=3600s ^ bytes=13

get user:42
# VALUE user:42 0 13
# hello, world!
# END

get user:42 user:43
# multiple keys in one request (response per key)

delete user:42
# DELETED

incr counter 1
decr counter 1

# Python (pymemcache)
from pymemcache.client.base import Client
c = Client(("localhost", 11211))
c.set("user:42", b"hello, world!", expire=3600, flags=0)
print(c.get("user:42"))   # b"hello, world!"

Explanation

set writes a value (overwriting any existing); get reads it. The text-protocol line is: <cmd> <key> <flags> <exptime> <bytes> then the data on the next line. flags is an opaque 16-bit int you can use for serialization hints (e.g. 1 = json). exptime is in seconds (0 = no ttl; <=30 days); unix timestamps >30 days are interpreted as absolute. get accepts multiple keys at once for batching. Values are byte strings — serialize JSON/pickle in your client. Keys are max 250 chars, no spaces/newlines.

More Memcached Snippets