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

REDIS
SET mykey "Hello Redis"
OK

A successful SET returns OK.

SET Command Parameters

SET supports multiple optional parameters for different setting strategies:

REDIS
# 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
💡 Distributed lock implementation: 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

BASH
# 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
▶ Try it Yourself

GET Command in Detail

The GET command retrieves the value of a key.

Basic Usage

REDIS
SET mykey "Hello Redis"
GET mykey
"Hello Redis"

Key Does Not Exist

REDIS
GET notexist
(nil)

Returns (nil) when the key does not exist.

GET Command Variants

REDIS
# 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"
⚠️ Note: GETRANGE indexes start from 0 and include the end position. 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

REDIS
SET temp "temporary"
DEL temp
(integer) 1  # Returns the number of deleted keys

Delete Multiple Keys

REDIS
SET key1 "value1"
SET key2 "value2"
SET key3 "value3"

DEL key1 key2 key3
(integer) 3  # Deleted 3 keys

Delete Non-existent Key

REDIS
DEL notexist
(integer) 0  # Deleted 0 keys
💡 Return value: DEL returns the number of actually deleted keys, not the deleted value.

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

REDIS
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

REDIS
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

REDIS
# 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)
⚠️ Note: MSETNX is atomic — either all succeed or all fail.

STRLEN - Get Length

STRLEN returns the length of a string value (in bytes).

Basic Usage

REDIS
SET mykey "Hello Redis"
STRLEN mykey
(integer) 11

SET text "Hello"
STRLEN text
(integer) 5

Key Does Not Exist

REDIS
STRLEN notexist
(integer) 0

APPEND - Append to String

The APPEND command appends content to the end of a string.

Basic Usage

REDIS
SET mykey "Hello"
APPEND mykey " Redis"
(integer) 11  # Returns total length after appending

GET mykey
"Hello Redis"

Appending to a Non-existent Key

REDIS
APPEND newkey "value"
(integer) 5  # Equivalent to SET newkey "value"

GET newkey
"value"
💡 Use case: APPEND can be used for building logs, concatenating URLs, etc.

String Use Cases

Use Case 1: Caching

REDIS
# 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

REDIS
# 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

REDIS
# 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

REDIS
# Store verification code (5-minute expiration)
SET code:phone:13800138000 "123456" EX 300

# Verify
GET code:phone:13800138000

Use Case 5: Rate Limiting

REDIS
# 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

REDIS
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"
ℹ️ Note: Encoding is automatically selected by Redis — no manual intervention needed. Understanding encoding helps optimize memory usage.

❓ FAQ

Q Does SET overwrite an existing key?
A Yes. By default, SET overwrites an existing key. Use the NX parameter to set only if the key does not exist.
Q How do I implement "update only if key exists"?
A Use the XX parameter of SET: SET key value XX. It only sets the new value if the key already exists.
Q What's the difference between MSET and multiple SETs?
A MSET is an atomic operation that completes multiple settings in one network round trip, making it more efficient. Multiple SETs require multiple round trips.
Q What's the maximum size of a string?
A Maximum 512MB. However, storing very large strings is not recommended as it affects performance and memory.
Q How do I store binary data (like images)?
A Redis strings are binary-safe and can store them directly. However, it's recommended to store image URLs or use dedicated file storage services.

📖 Summary

📝 Exercises

  1. Basic operations: Use SET to store your name, age, and city, then retrieve them all at once with MGET
  2. Expiration practice: Set a key with a TTL and check remaining time with TTL
  3. Distributed lock: Implement a simple distributed lock using SET NX EX, try acquiring and releasing it
  4. 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.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏