Strings, numbers and keys
The string is Redis's simplest type, and its most used. A string value can hold text, a number, JSON, or even binary data like an image (up to 512 MB, though you should keep values small).
SET and GET
SET overwrites whatever was there. Quotes are only needed when a value contains spaces.
Conditional SET
| Option | Only set if… |
|---|---|
NX |
the key does not exist (create only) |
XX |
the key already exists (update only) |
GET |
(not a condition) also return the old value |
SET … NX is how you claim something exactly once, for example "reserve this username", because the check and the write happen as one atomic step.
Several keys at once
MSET and MGET handle many keys in one round trip, which is much faster than many separate commands over a network:
Numbers and atomic counters
Redis stores strings, but if a string looks like an integer, you can do arithmetic on it:
INCR on a missing key starts from 0. Most importantly, INCR is atomic: if 1,000 requests run INCR views at the same moment, the result is exactly 1,000 higher. Compare reading the value, adding 1 in your app and writing it back, which loses updates when requests overlap.
Working with keys
KEYS vs SCAN
KEYS pattern walks every key in one go. On a production server with millions of keys, that blocks Redis for seconds, and everything else waits. Never use KEYS in production. Use SCAN, which returns a few keys at a time with a cursor:
Each reply is 1) next cursor and 2) keys found. Keep calling SCAN with the returned cursor until it comes back as "0". (A page may contain fewer keys than COUNT, or none: that's normal.)
Multiple databases
A Redis server has 16 numbered databases (0–15). SELECT switches between them, and the prompt shows the number:
In practice most apps use only database 0 and separate data with key prefixes. Redis Cluster supports only database 0.
How Redis stores small values
Redis picks a compact internal encoding depending on the value:
int for integers, embstr for short strings and raw for longer ones. You rarely need this, but it explains why many small keys are memory-efficient.
Practice
- Create a counter
downloads:appand increment it by 1, then by 25. - Use
SET … NXto "reserve" the usernameneo, then try to reserve it again. - Store three products' stock with one
MSET, then read them with oneMGET.
1.What does SET lock:job42 1 NX do if the key already exists?
2.Why is INCR better than GET + add 1 + SET in your app?
3.Why shouldn't you run KEYS * on a production server?