SET & GET
SET and GET — the core of Redis strings
Section titled “SET and GET — the core of Redis strings”SET key value stores a string. GET key retrieves it. If the key already exists, SET overwrites it unconditionally (unless you add a condition flag).
127.0.0.1:6379> SET city "Bangkok"OK127.0.0.1:6379> GET city"Bangkok"127.0.0.1:6379> SET city "Chiang Mai"OK127.0.0.1:6379> GET city"Chiang Mai"SET options
Section titled “SET options”Redis 7 SET supports several options in one command:
| Option | Meaning |
|---|---|
EX seconds | Set expiration in seconds |
PX milliseconds | Set expiration in milliseconds |
EXAT unix-time-seconds | Expire at a Unix timestamp (seconds) |
PXAT unix-time-ms | Expire at a Unix timestamp (milliseconds) |
NX | Only set if the key does not exist |
XX | Only set if the key does exist |
GET | Return the old value before overwriting |
KEEPTTL | Retain the existing TTL instead of resetting it |
127.0.0.1:6379> SET token "abc123" EX 60OK127.0.0.1:6379> TTL token(integer) 59127.0.0.1:6379> SET counter 0 NXOK127.0.0.1:6379> SET counter 99 NX(nil)127.0.0.1:6379> GET counter"0"127.0.0.1:6379> SET city "Phuket" GET"Chiang Mai"127.0.0.1:6379> GET city"Phuket"SET token "abc123" EX 60
TTL token
SET counter 0 NX
SET counter 99 NX
GET counter
SET city "Phuket" GET
GET citySETEX and SETNX
Section titled “SETEX and SETNX”These are older convenience aliases — SET with EX or NX is preferred in Redis 7, but you will still see them in legacy code:
127.0.0.1:6379> SETEX session:user1 3600 "token-xyz"OK127.0.0.1:6379> TTL session:user1(integer) 3599127.0.0.1:6379> SETNX lock:job1 "worker-A"(integer) 1127.0.0.1:6379> SETNX lock:job1 "worker-B"(integer) 0127.0.0.1:6379> GET lock:job1"worker-A"SETEX session:user1 3600 "token-xyz"
TTL session:user1
SETNX lock:job1 "worker-A"
SETNX lock:job1 "worker-B"
GET lock:job1MSET and MGET — batch operations
Section titled “MSET and MGET — batch operations”Set or get many keys in a single round-trip. This is significantly faster than individual commands when you need multiple keys at once.
127.0.0.1:6379> MSET user:1:name "Ada" user:1:lang "Python" user:2:name "Bob" user:2:lang "Go"OK127.0.0.1:6379> MGET user:1:name user:1:lang user:2:name user:2:lang1) "Ada"2) "Python"3) "Bob"4) "Go"127.0.0.1:6379> MGET user:1:name user:99:name1) "Ada"2) (nil)MSET user:1:name "Ada" user:1:lang "Python" user:2:name "Bob" user:2:lang "Go"
MGET user:1:name user:1:lang user:2:name user:2:lang
MGET user:1:name user:99:nameAPPEND and STRLEN
Section titled “APPEND and STRLEN”APPEND adds to the end of an existing string value (or creates the key if absent). STRLEN returns the byte length of the value.
127.0.0.1:6379> SET log "2024-01-01 boot"OK127.0.0.1:6379> APPEND log " | 2024-01-01 ready"(integer) 34127.0.0.1:6379> GET log"2024-01-01 boot | 2024-01-01 ready"127.0.0.1:6379> STRLEN log(integer) 34SET log "2024-01-01 boot"
APPEND log " | 2024-01-01 ready"
GET log
STRLEN log