redis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Redis

Redis

Caching, data structures, and real-time patterns.
缓存、数据结构与实时模式

CLI Basics

CLI基础

bash
undefined
bash
undefined

Connect

Connect

redis-cli redis-cli -h hostname -p 6379 -a password
redis-cli redis-cli -h hostname -p 6379 -a password

Ping

Ping

redis-cli ping # PONG
redis-cli ping # PONG

Info

Info

redis-cli info redis-cli info memory redis-cli info keyspace
undefined
redis-cli info redis-cli info memory redis-cli info keyspace
undefined

Strings

字符串类型

bash
undefined
bash
undefined

Set/get

Set/get

SET key "value" GET key
SET key "value" GET key

With expiration

With expiration

SET session:abc "user123" EX 3600 # 1 hour SETEX session:abc 3600 "user123" # Same thing
SET session:abc "user123" EX 3600 # 1 hour SETEX session:abc 3600 "user123" # Same thing

Set if not exists

Set if not exists

SETNX lock:resource "owner123"
SETNX lock:resource "owner123"

Increment/decrement

Increment/decrement

INCR counter INCRBY counter 5 DECR counter
INCR counter INCRBY counter 5 DECR counter

Multiple

Multiple

MSET key1 "val1" key2 "val2" MGET key1 key2
undefined
MSET key1 "val1" key2 "val2" MGET key1 key2
undefined

Hashes

哈希类型

bash
undefined
bash
undefined

Set fields

Set fields

HSET user:1 name "Alice" email "alice@test.com" age 30
HSET user:1 name "Alice" email "alice@test.com" age 30

Get

Get

HGET user:1 name HGETALL user:1 HMGET user:1 name email
HGET user:1 name HGETALL user:1 HMGET user:1 name email

Increment field

Increment field

HINCRBY user:1 age 1
HINCRBY user:1 age 1

Check existence

Check existence

HEXISTS user:1 email
HEXISTS user:1 email

Delete field

Delete field

HDEL user:1 age
undefined
HDEL user:1 age
undefined

Lists

列表类型

bash
undefined
bash
undefined

Push

Push

LPUSH queue "task1" # Left (head) RPUSH queue "task2" # Right (tail)
LPUSH queue "task1" # Left (head) RPUSH queue "task2" # Right (tail)

Pop

Pop

LPOP queue # Left RPOP queue # Right BLPOP queue 30 # Blocking pop (timeout 30s)
LPOP queue # Left RPOP queue # Right BLPOP queue 30 # Blocking pop (timeout 30s)

Range

Range

LRANGE queue 0 -1 # All elements LRANGE queue 0 9 # First 10
LRANGE queue 0 -1 # All elements LRANGE queue 0 9 # First 10

Length

Length

LLEN queue
LLEN queue

Trim (keep only range)

Trim (keep only range)

LTRIM queue 0 99 # Keep first 100
undefined
LTRIM queue 0 99 # Keep first 100
undefined

Sets

集合类型

bash
undefined
bash
undefined

Add/remove

Add/remove

SADD tags "python" "redis" "docker" SREM tags "docker"
SADD tags "python" "redis" "docker" SREM tags "docker"

Check membership

Check membership

SISMEMBER tags "python"
SISMEMBER tags "python"

All members

All members

SMEMBERS tags
SMEMBERS tags

Count

Count

SCARD tags
SCARD tags

Operations

Operations

SUNION tags1 tags2 # Union SINTER tags1 tags2 # Intersection SDIFF tags1 tags2 # Difference
SUNION tags1 tags2 # Union SINTER tags1 tags2 # Intersection SDIFF tags1 tags2 # Difference

Random

Random

SRANDMEMBER tags 2 # 2 random members
undefined
SRANDMEMBER tags 2 # 2 random members
undefined

Sorted Sets

有序集合类型

bash
undefined
bash
undefined

Add with score

Add with score

ZADD leaderboard 100 "alice" 95 "bob" 87 "charlie"
ZADD leaderboard 100 "alice" 95 "bob" 87 "charlie"

Get by rank

Get by rank

ZRANGE leaderboard 0 -1 WITHSCORES # Ascending ZREVRANGE leaderboard 0 2 WITHSCORES # Top 3
ZRANGE leaderboard 0 -1 WITHSCORES # Ascending ZREVRANGE leaderboard 0 2 WITHSCORES # Top 3

Get by score

Get by score

ZRANGEBYSCORE leaderboard 90 100 # Score 90-100
ZRANGEBYSCORE leaderboard 90 100 # Score 90-100

Rank

Rank

ZRANK leaderboard "alice" # 0-based position ZREVRANK leaderboard "alice" # Reverse rank
ZRANK leaderboard "alice" # 0-based position ZREVRANK leaderboard "alice" # Reverse rank

Increment score

Increment score

ZINCRBY leaderboard 5 "bob"
ZINCRBY leaderboard 5 "bob"

Count in range

Count in range

ZCOUNT leaderboard 80 100
undefined
ZCOUNT leaderboard 80 100
undefined

Key Management

键管理

bash
undefined
bash
undefined

Find keys

Find keys

KEYS user:* # Pattern match (avoid in production) SCAN 0 MATCH user:* COUNT 100 # Safe iteration
KEYS user:* # Pattern match (avoid in production) SCAN 0 MATCH user:* COUNT 100 # Safe iteration

Expiration

Expiration

EXPIRE key 3600 # Set TTL (seconds) PEXPIRE key 3600000 # Milliseconds TTL key # Check TTL PERSIST key # Remove expiration
EXPIRE key 3600 # Set TTL (seconds) PEXPIRE key 3600000 # Milliseconds TTL key # Check TTL PERSIST key # Remove expiration

Delete

Delete

DEL key UNLINK key # Async delete (large keys)
DEL key UNLINK key # Async delete (large keys)

Type

Type

TYPE key
TYPE key

Exists

Exists

EXISTS key
undefined
EXISTS key
undefined

Pub/Sub

发布/订阅(Pub/Sub)

bash
undefined
bash
undefined

Subscribe

Subscribe

SUBSCRIBE channel1 channel2
SUBSCRIBE channel1 channel2

Pattern subscribe

Pattern subscribe

PSUBSCRIBE news.*
PSUBSCRIBE news.*

Publish

Publish

PUBLISH channel1 "Hello subscribers!"
PUBLISH channel1 "Hello subscribers!"

Unsubscribe

Unsubscribe

UNSUBSCRIBE channel1
undefined
UNSUBSCRIBE channel1
undefined

Common Patterns

常见模式

Caching

缓存

bash
undefined
bash
undefined

Cache-aside pattern

Cache-aside pattern

1. Check cache

1. Check cache

GET cache:user:1
GET cache:user:1

2. If miss, query DB, then set cache

2. If miss, query DB, then set cache

SET cache:user:1 '{"name":"Alice"}' EX 300 # 5 min TTL
undefined
SET cache:user:1 '{"name":"Alice"}' EX 300 # 5 min TTL
undefined

Rate Limiting

限流

bash
undefined
bash
undefined

Sliding window rate limit

Sliding window rate limit

Using sorted set with timestamp scores

Using sorted set with timestamp scores

ZADD ratelimit:user:1 <timestamp> <request-id> ZREMRANGEBYSCORE ratelimit:user:1 0 <timestamp-window-ago> ZCARD ratelimit:user:1
ZADD ratelimit:user:1 <timestamp> <request-id> ZREMRANGEBYSCORE ratelimit:user:1 0 <timestamp-window-ago> ZCARD ratelimit:user:1

If count > limit, reject

If count > limit, reject

undefined
undefined

Session Store

会话存储

bash
SET session:<session-id> '{"userId":1,"role":"admin"}' EX 86400
GET session:<session-id>
bash
SET session:<session-id> '{"userId":1,"role":"admin"}' EX 86400
GET session:<session-id>

Distributed Lock

分布式锁

bash
undefined
bash
undefined

Acquire lock

Acquire lock

SET lock:resource <unique-id> NX EX 30
SET lock:resource <unique-id> NX EX 30

NX = only if not exists, EX = auto-expire

NX = only if not exists, EX = auto-expire

Release lock (use Lua for atomicity)

Release lock (use Lua for atomicity)

EVAL "if redis.call('GET',KEYS[1]) == ARGV[1] then return redis.call('DEL',KEYS[1]) else return 0 end" 1 lock:resource <unique-id>
undefined
EVAL "if redis.call('GET',KEYS[1]) == ARGV[1] then return redis.call('DEL',KEYS[1]) else return 0 end" 1 lock:resource <unique-id>
undefined

Configuration

配置

bash
undefined
bash
undefined

Max memory

Max memory

CONFIG SET maxmemory 256mb CONFIG SET maxmemory-policy allkeys-lru
CONFIG SET maxmemory 256mb CONFIG SET maxmemory-policy allkeys-lru

Eviction policies:

Eviction policies:

noeviction - Return error on write when full

noeviction - Return error on write when full

allkeys-lru - Evict least recently used

allkeys-lru - Evict least recently used

allkeys-lfu - Evict least frequently used

allkeys-lfu - Evict least frequently used

volatile-lru - LRU among keys with TTL

volatile-lru - LRU among keys with TTL

volatile-ttl - Evict shortest TTL first

volatile-ttl - Evict shortest TTL first

Persistence

Persistence

CONFIG SET save "900 1 300 10" # RDB snapshots CONFIG SET appendonly yes # AOF log
CONFIG SET save "900 1 300 10" # RDB snapshots CONFIG SET appendonly yes # AOF log

View config

View config

CONFIG GET maxmemory*
undefined
CONFIG GET maxmemory*
undefined

Reference

参考资料

For caching patterns, pub/sub, and Lua scripts:
references/patterns.md
关于缓存模式、发布/订阅及Lua脚本的更多内容,请参考:
references/patterns.md