Redis Strings (Part 2)

This lesson covers numeric operations and bit operations on strings, enabling use cases such as counters and statistics.

Numeric Operations

Redis strings can store integers and support atomic numeric operations.

INCR and DECR: Increment and Decrement

REDIS
# Set initial value
SET counter 10

# Increment by 1
INCR counter
(integer) 11

# Decrement by 1
DECR counter
(integer) 10
💡 Atomicity: INCR and DECR are atomic operations. Multiple clients can INCR simultaneously without conflicts, making them ideal for counters.

INCRBY and DECRBY: Specify Increment Amount

REDIS
SET counter 100

# Increase by 10
INCRBY counter 10
(integer) 110

# Decrease by 20
DECRBY counter 20
(integer) 90

INCRBYFLOAT: Floating-Point Operations

REDIS
SET price 10.5

# Increase by 2.3
INCRBYFLOAT price 2.3
"12.8"

# Decrease by 1.5 (pass a negative number)
INCRBYFLOAT price -1.5
"11.3"
⚠️ Note: INCRBYFLOAT returns a floating-point number in string format, not an integer.

Limitations of Numeric Operations

REDIS
# Operations on non-numeric strings will fail
SET text "hello"
INCR text
(error) ERR value is not an integer or out of range

# Operating on a non-existent key (starts from 0)
INCR newcounter
(integer) 1  # Incremented from 0 to 1

Use Case: Counters

REDIS
# Article view count
INCR article:123:views
(integer) 1

# User like count
INCR user:456:likes
(integer) 1

# API call count
INCR api:usage:20260623
(integer) 1

Range Operations

GETRANGE: Get Substring

REDIS
SET message "Hello Redis World"

# Get first 5 characters
GETRANGE message 0 4
"Hello"

# Get middle part
GETRANGE message 6 10
"Redis"

# Get last 5 characters
GETRANGE message -5 -1
"World"

# Get entire string
GETRANGE message 0 -1
"Hello Redis World"
💡 Index rules:

  • Indexes start from 0
  • The end position is inclusive
  • Negative indexes count from the end (-1 is the last character)

SETRANGE: Replace Substring

REDIS
SET message "Hello World"

# Replace starting at position 6
SETRANGE message 6 "Redis"
(integer) 11  # Returns the string length

GET message
"Hello Redis"

# Replace beyond the original length (auto-fills)
SET short "Hi"
SETRANGE short 5 "There"
(integer) 10

GET short
"Hi\x00\x00\x00There"  # Filled with null bytes in between
⚠️ Note: If SETRANGE extends beyond the original string length, the gap is filled with null bytes (\x00).

Bit Operations

Redis strings support bit operations, useful for Bloom filters, bitmap statistics, etc.

SETBIT and GETBIT: Set and Get Bits

REDIS
# Set bitmap (initially all 0s)
SETBIT mybitmap 0 1
(integer) 0  # Returns old value

SETBIT mybitmap 2 1
(integer) 0

SETBIT mybitmap 7 1
(integer) 0

# Get bit value
GETBIT mybitmap 0
(integer) 1

GETBIT mybitmap 1
(integer) 0

GETBIT mybitmap 2
(integer) 1

BITCOUNT: Count Bits Set to 1

REDIS
# Count all bits
BITCOUNT mybitmap
(integer) 3  # 3 bits are set to 1

# Count within a byte range
BITCOUNT mybitmap 0 0
(integer) 3  # Byte 0 has 3 bits set to 1

BITOP: Bitwise Operations

REDIS
# Create two bitmaps
SETBIT bitmap1 0 1
SETBIT bitmap1 1 1
SETBIT bitmap2 1 1
SETBIT bitmap2 2 1

# AND
BITOP AND result bitmap1 bitmap2
(integer) 1

GETBIT result 1
(integer) 1  # Only bit 1 is 1 in both

# OR
BITOP OR result bitmap1 bitmap2
(integer) 1

# XOR
BITOP XOR result bitmap1 bitmap2
(integer) 1

# NOT (only supports one key)
BITOP NOT result bitmap1
(integer) 1

BITPOS: Find First 0 or 1 Position

REDIS
SET mykey "\xff\xf0\x00"  # Binary: 11111111 11110000 00000000

# Find first 0
BITPOS mykey 0
(integer) 12  # Bit 12 is the first 0

# Find first 1
BITPOS mykey 1
(integer) 0  # Bit 0 is the first 1

# Find within a byte range
BITPOS mykey 1 1 2
(integer) 8  # Within bytes 1-2, bit 8 is the first 1

Use Case: User Check-in

REDIS
# User ID 123 checks in on June 23, 2026 (day 174 of the year)
SETBIT user:123:signin:2026 174 1

# Check if checked in
GETBIT user:123:signin:2026 174
(integer) 1

# Count total check-ins for the year
BITCOUNT user:123:signin:2026
(integer) 50  # Checked in 50 days

# Check consecutive check-ins (requires BITPOS and business logic)

Use Case: Online User Statistics

REDIS
# User 123 comes online
SETBIT online:users 123 1

# User 456 comes online
SETBIT online:users 456 1

# Count online users
BITCOUNT online:users
(integer) 2

# User 123 goes offline
SETBIT online:users 123 0

Practical String Tips

1. Generate Unique IDs

REDIS
# Use INCR to generate auto-incrementing IDs
SET next:user:id 1000

INCR next:user:id
(integer) 1001  # New user ID

INCR next:user:id
(integer) 1002

2. Rate Limiting Counter

REDIS
# API rate limit: max 100 times per minute
SET limit:api:user:1 0 EX 60

INCR limit:api:user:1
(integer) 1

# Check if limit is exceeded
GET limit:api:user:1
"50"  # Currently called 50 times

3. Distributed Sequence Number

REDIS
# Order number generation
SET order:sequence 1000000000

INCR order:sequence
(integer) 1000000001  # New order number

4. UV (Unique Visitors) Statistics

REDIS
# Use bitmap for UV statistics
SETBIT uv:20260623 12345 1  # User ID 12345 visited
SETBIT uv:20260623 67890 1  # User ID 67890 visited

# Count UV
BITCOUNT uv:20260623
(integer) 2  # 2 unique visitors

Performance Optimization Tips

1. Use Batch Operations

REDIS
# ❌ Multiple individual operations
SET key1 "value1"
SET key2 "value2"
SET key3 "value3"

# ✅ Batch operation
MSET key1 "value1" key2 "value2" key3 "value3"

2. Set Reasonable Expiration

REDIS
# Set expiration for cached data
SET cache:key "value" EX 3600

# Avoid cache avalanche: add random jitter to TTL
SET cache:key "value" EX 3600

3. Choose the Right Encoding

REDIS
# Short strings use embstr encoding (<= 44 bytes)
SET short "Hello Redis"

# Long strings use raw encoding
SET long "This is a very long string..."

# Check encoding
OBJECT ENCODING short
"embstr"

❓ FAQ

Q Can INCR overflow?
A Yes. Redis integers are 64-bit signed integers (range: -2^63 to 2^63-1). Going out of range will return an error.
Q How do I implement a floating-point counter?
A Use the INCRBYFLOAT command, but note that it returns a string format.
Q What are practical uses for bit operations?
A Bitmaps can be used for user check-ins, online user statistics, Bloom filters, permission bits — very memory-efficient.
Q What is the time complexity of GETRANGE?
A O(N), where N is the length of the returned substring. Getting short substrings is very fast.
Q How do I store large text (like article content)?
A Consider compressing it first, or sharding it. A better approach is to store it in a file system or object storage and keep only the URL in Redis.

📖 Summary

📝 Exercises

  1. Counter: Implement an article view counter, simulate 10 views, and check the final count
  2. Range operations: Set a long string and use GETRANGE to retrieve different parts
  3. Bitmap check-in: Use a bitmap to implement user check-in and count check-in days
  4. UV statistics: Use a bitmap to track website UVs, simulating multiple user visits

Next Lesson

In the next lesson, we will learn Redis Hashes (Part 1), covering basic hash operations.

100%

🙏 帮我们做得更好

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

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