Redis Strings (Part 1)
Strings are the most basic Redis data type. This lesson covers basic string operation commands.
SET Command in Detail
The SET command sets a key-value pair and is the most commonly used Redis command.
Basic Usage
SET mykey "Hello Redis"
OK
A successful SET returns OK.
SET Command Parameters
SET supports multiple optional parameters for different setting strategies:
# EX: set expiration in seconds
SET session:token "user_data" EX 3600
# PX: set expiration in milliseconds
SET cache:key "value" PX 60000
# NX: set only if key does not exist
SET lock:resource "locked" NX
# XX: set only if key exists
SET counter 100 XX
# Combined: set a lock with expiration
SET lock:order:123 "locked" NX EX 10
Parameter Reference
| Parameter | Description | Example |
|---|---|---|
| EX seconds | Set expiration in seconds | SET key value EX 60 |
| PX milliseconds | Set expiration in milliseconds | SET key value PX 60000 |
| EXAT timestamp | Set expiration Unix timestamp (seconds) | SET key value EXAT 1700000000 |
| PXAT timestamp | Set expiration Unix timestamp (milliseconds) | SET key value PXAT 1700000000000 |
| NX | Set only if key does not exist | SET key value NX |
| XX | Set only if key exists | SET key value XX |
| GET | Return the old value (Redis 6.2+) | SET key value GET |
| KEEPTTL | Keep the existing TTL | SET key value KEEPTTL |
SET lock:resource "value" NX EX 10 is the classic way to implement distributed locks. NX ensures atomicity, EX prevents deadlocks.
Example: Implementing a Distributed Lock
# Acquire lock (set only if lock doesn't exist, auto-release after 10 seconds)
SET lock:product:123 "order_process" NX EX 10
# Release lock (delete the key)
DEL lock:product:123
GET Command in Detail
The GET command retrieves the value of a key.
Basic Usage
SET mykey "Hello Redis"
GET mykey
"Hello Redis"
Key Does Not Exist
GET notexist
(nil)
Returns (nil) when the key does not exist.
GET Command Variants
# GETSET: get old value and set new value
SET counter 100
GETSET counter 0
"100" # Returns old value
GET counter
"0" # Updated to new value
# GETRANGE: get substring of a string
SET message "Hello Redis World"
GETRANGE message 0 4
"Hello"
GETRANGE message 6 10
"Redis"
GETRANGE key 0 4 gets characters at positions 0 through 4 (5 characters total).
DEL - Delete Keys
The DEL command deletes one or more keys.
Delete a Single Key
SET temp "temporary"
DEL temp
(integer) 1 # Returns the number of deleted keys
Delete Multiple Keys
SET key1 "value1"
SET key2 "value2"
SET key3 "value3"
DEL key1 key2 key3
(integer) 3 # Deleted 3 keys
Delete Non-existent Key
DEL notexist
(integer) 0 # Deleted 0 keys
MSET and MGET Batch Operations
MSET and MGET can set or get multiple key-value pairs in one go, reducing network round trips.
MSET Batch Setting
MSET user:1:name "Alice" user:1:age "25" user:1:city "Beijing"
OK
# Equivalent to
SET user:1:name "Alice"
SET user:1:age "25"
SET user:1:city "Beijing"
MGET Batch Getting
MGET user:1:name user:1:age user:1:city
1) "Alice"
2) "25"
3) "Beijing"
# Including non-existent keys
MGET user:1:name user:1:email user:1:age
1) "Alice"
2) (nil) # Key does not exist
3) "25"
MSETNX: Set Only If None of the Keys Exist
# Set only if none of the keys exist
MSETNX key1 "value1" key2 "value2"
(integer) 1 # Success
# Try again (key1 and key2 already exist)
MSETNX key1 "new1" key3 "value3"
(integer) 0 # Failed, key1 already exists
# Verify: key3 was not set
GET key3
(nil)
STRLEN - Get Length
STRLEN returns the length of a string value (in bytes).
Basic Usage
SET mykey "Hello Redis"
STRLEN mykey
(integer) 11
SET text "Hello"
STRLEN text
(integer) 5
Key Does Not Exist
STRLEN notexist
(integer) 0
APPEND - Append to String
The APPEND command appends content to the end of a string.
Basic Usage
SET mykey "Hello"
APPEND mykey " Redis"
(integer) 11 # Returns total length after appending
GET mykey
"Hello Redis"
Appending to a Non-existent Key
APPEND newkey "value"
(integer) 5 # Equivalent to SET newkey "value"
GET newkey
"value"
String Use Cases
Use Case 1: Caching
# Cache API response
SET cache:api:user:1 '{"name":"Alice","age":25}' EX 300
# Get cached data
GET cache:api:user:1
Use Case 2: Session Storage
# Store user session (30-minute expiration)
SET session:token:abc123 '{"user_id":1,"role":"admin"}' EX 1800
# Validate session
GET session:token:abc123
Use Case 3: Distributed Lock
# Acquire lock (auto-release after 10 seconds)
SET lock:order:process "server1" NX EX 10
# Returns OK means lock acquired
# Returns nil means lock is held by another process
# Release lock
DEL lock:order:process
Use Case 4: Verification Code
# Store verification code (5-minute expiration)
SET code:phone:13800138000 "123456" EX 300
# Verify
GET code:phone:13800138000
Use Case 5: Rate Limiting
# Record API access count (1-minute window)
SET limit:api:user:1 "0" EX 60
# Increment on each access (needs to be used with INCR)
String Encoding Optimization
Redis automatically selects the optimal encoding based on string content:
| Encoding | Condition | Description |
|---|---|---|
| int | Integer value within long range | Integer encoding, saves memory |
| embstr | String length <= 44 bytes | Embedded string, compact storage |
| raw | String length > 44 bytes | Regular string, uses SDS |
Checking Encoding Type
SET intkey 12345
OBJECT ENCODING intkey
"int"
SET shortkey "Hello"
OBJECT ENCODING shortkey
"embstr"
SET longkey "This is a very long string that exceeds 44 bytes limit"
OBJECT ENCODING longkey
"raw"
❓ FAQ
SET key value XX. It only sets the new value if the key already exists.📖 Summary
- SET sets a key-value pair, supports EX/PX/NX/XX parameters
- GET retrieves a value, returns nil if key doesn't exist
- DEL deletes keys, returns the actual number deleted
- MSET/MGET for batch operations, reducing network round trips
- STRLEN gets string length, APPEND appends to string
- Strings are commonly used for caching, sessions, distributed locks, verification codes
- Redis automatically selects optimal encoding (int/embstr/raw)
📝 Exercises
- Basic operations: Use SET to store your name, age, and city, then retrieve them all at once with MGET
- Expiration practice: Set a key with a TTL and check remaining time with TTL
- Distributed lock: Implement a simple distributed lock using SET NX EX, try acquiring and releasing it
- Batch operations: Use MSET to set 10 keys, then use MGET to get 5 of them
Next Lesson
In the next lesson, we will learn Redis Strings (Part 2), covering numeric operations and bit operations.



