redis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Redis

Redis

Configure, operate, and optimize Redis for caching, queues, rate limiting, and real-time data storage.
配置、操作和优化Redis,用于缓存、队列、限流和实时数据存储。

When to Use

使用场景

  • You need a low-latency in-memory cache to reduce database load.
  • Your application requires rate limiting, session storage, or leaderboards.
  • You need pub/sub messaging between services.
  • You want a distributed lock or job queue backed by an in-memory store.
  • 需要低延迟的内存缓存来降低数据库负载。
  • 应用需要限流、会话存储或排行榜功能。
  • 需要服务间的发布/订阅消息机制。
  • 需要基于内存存储的分布式锁或任务队列。

Prerequisites

前置条件

  • Linux server or Docker.
  • Root or sudo access for package installation.
  • Redis 7.x recommended for production.
  • Linux服务器或Docker环境。
  • 安装软件包所需的Root或sudo权限。
  • 生产环境推荐使用Redis 7.x版本。

Installation and Setup

安装与设置

bash
undefined
bash
undefined

Debian / Ubuntu

Debian / Ubuntu

sudo apt update sudo apt install -y redis-server
sudo apt update sudo apt install -y redis-server

RHEL / Amazon Linux

RHEL / Amazon Linux

sudo dnf install -y redis
sudo dnf install -y redis

Start and enable

启动并设置开机自启

sudo systemctl enable --now redis-server
sudo systemctl enable --now redis-server

Verify

验证

redis-cli ping
redis-cli ping

Expected output: PONG

预期输出:PONG

undefined
undefined

Core Configuration

核心配置

Edit
/etc/redis/redis.conf
:
ini
undefined
编辑
/etc/redis/redis.conf
:
ini
undefined

Network

网络配置

bind 0.0.0.0 port 6379 protected-mode yes requirepass strong_redis_password
bind 0.0.0.0 port 6379 protected-mode yes requirepass strong_redis_password

Memory

内存配置

maxmemory 2gb maxmemory-policy allkeys-lru
maxmemory 2gb maxmemory-policy allkeys-lru

Connections

连接配置

maxclients 10000 timeout 300 tcp-keepalive 60
maxclients 10000 timeout 300 tcp-keepalive 60

Logging

日志配置

loglevel notice logfile /var/log/redis/redis-server.log
loglevel notice logfile /var/log/redis/redis-server.log

Security — disable dangerous commands in production

安全配置——生产环境禁用危险命令

rename-command FLUSHALL "" rename-command FLUSHDB "" rename-command CONFIG "" rename-command DEBUG ""

```bash
sudo systemctl restart redis-server
rename-command FLUSHALL "" rename-command FLUSHDB "" rename-command CONFIG "" rename-command DEBUG ""

```bash
sudo systemctl restart redis-server

redis-cli Commands Reference

redis-cli命令参考

bash
undefined
bash
undefined

Connect with authentication

带认证连接

redis-cli -a strong_redis_password
redis-cli -a strong_redis_password

Connect to a remote host

连接远程主机

redis-cli -h 10.0.0.5 -p 6379 -a strong_redis_password
undefined
redis-cli -h 10.0.0.5 -p 6379 -a strong_redis_password
undefined

String Operations

字符串操作

SET user:1:name "Alice"
GET user:1:name
SET user:1:name "Alice"
GET user:1:name

Set with TTL (seconds)

设置带TTL(秒)的键

SETEX session:abc123 3600 '{"userId":1}'
SETEX session:abc123 3600 '{"userId":1}'

Set only if key does not exist (distributed lock pattern)

仅当键不存在时设置(分布式锁模式)

SET lock:order:42 "worker-1" NX EX 30
SET lock:order:42 "worker-1" NX EX 30

Increment counters

计数器递增

INCR page:views:/home INCRBY api:quota:user:1 -1
undefined
INCR page:views:/home INCRBY api:quota:user:1 -1
undefined

Hash Operations

哈希操作

HSET user:1 name "Alice" email "alice@example.com" plan "pro"
HGET user:1 email
HGETALL user:1
HINCRBY user:1 login_count 1
HSET user:1 name "Alice" email "alice@example.com" plan "pro"
HGET user:1 email
HGETALL user:1
HINCRBY user:1 login_count 1

List Operations (Queues)

列表操作(队列)

LPUSH queue:emails '{"to":"alice@example.com","subject":"Welcome"}'
RPOP queue:emails
LLEN queue:emails
LPUSH queue:emails '{"to":"alice@example.com","subject":"Welcome"}'
RPOP queue:emails
LLEN queue:emails

Blocking pop (worker pattern)

阻塞式弹出(工作者模式)

BRPOP queue:emails 30
undefined
BRPOP queue:emails 30
undefined

Set and Sorted Set Operations

集合与有序集合操作

undefined
undefined

Sets — unique tags

集合——唯一标签

SADD article:1:tags "redis" "database" "caching" SMEMBERS article:1:tags SISMEMBER article:1:tags "redis"
SADD article:1:tags "redis" "database" "caching" SMEMBERS article:1:tags SISMEMBER article:1:tags "redis"

Sorted sets — leaderboards

有序集合——排行榜

ZADD leaderboard 1500 "player:1" 2300 "player:2" 1800 "player:3" ZREVRANGE leaderboard 0 9 WITHSCORES ZINCRBY leaderboard 100 "player:1" ZRANK leaderboard "player:2"
undefined
ZADD leaderboard 1500 "player:1" 2300 "player:2" 1800 "player:3" ZREVRANGE leaderboard 0 9 WITHSCORES ZINCRBY leaderboard 100 "player:1" ZRANK leaderboard "player:2"
undefined

Key Management

键管理

KEYS user:*             # avoid in production — use SCAN instead
SCAN 0 MATCH user:* COUNT 100
TTL session:abc123
PERSIST session:abc123
DEL user:old
EXPIRE user:1 86400
TYPE user:1
KEYS user:*             # 生产环境避免使用——改用SCAN
SCAN 0 MATCH user:* COUNT 100
TTL session:abc123
PERSIST session:abc123
DEL user:old
EXPIRE user:1 86400
TYPE user:1

Persistence

持久化

RDB Snapshots

RDB快照

ini
undefined
ini
undefined

redis.conf — save snapshots at intervals

redis.conf —— 按时间间隔保存快照

save 900 1 # snapshot if >= 1 key changed in 900 seconds save 300 10 # snapshot if >= 10 keys changed in 300 seconds save 60 10000 # snapshot if >= 10000 keys changed in 60 seconds
dbfilename dump.rdb dir /var/lib/redis rdbcompression yes
undefined
save 900 1 # 900秒内至少1个键变更则保存快照 save 300 10 # 300秒内至少10个键变更则保存快照 save 60 10000 # 60秒内至少10000个键变更则保存快照
dbfilename dump.rdb dir /var/lib/redis rdbcompression yes
undefined

AOF (Append-Only File)

AOF(仅追加文件)

ini
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec    # good balance of safety and performance
ini
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec    # 安全性与性能的良好平衡

Options: always (safest, slowest), everysec (recommended), no (OS decides)

选项:always(最安全,最慢),everysec(推荐),no(由操作系统决定)

AOF rewrite thresholds

AOF重写阈值

auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb
undefined
auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb
undefined

Recommended Production Strategy

推荐生产环境策略

Use both RDB and AOF together. RDB provides fast restarts and compact backups. AOF provides durability down to 1-second granularity.
ini
save 900 1
save 300 10
appendonly yes
appendfsync everysec
同时使用RDB和AOF。RDB提供快速重启和紧凑备份,AOF提供秒级粒度的数据持久性。
ini
save 900 1
save 300 10
appendonly yes
appendfsync everysec

Redis Sentinel (High Availability)

Redis Sentinel(高可用)

Sentinel monitors Redis instances and performs automatic failover.
Sentinel用于监控Redis实例并执行自动故障转移。

Sentinel Configuration

Sentinel配置

ini
undefined
ini
undefined

/etc/redis/sentinel.conf

/etc/redis/sentinel.conf

port 26379 sentinel monitor mymaster 10.0.0.1 6379 2 sentinel auth-pass mymaster strong_redis_password sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 60000 sentinel parallel-syncs mymaster 1

Run at least three Sentinel instances for quorum.

```bash
port 26379 sentinel monitor mymaster 10.0.0.1 6379 2 sentinel auth-pass mymaster strong_redis_password sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 60000 sentinel parallel-syncs mymaster 1

至少运行3个Sentinel实例以满足仲裁要求。

```bash

Start Sentinel

启动Sentinel

redis-sentinel /etc/redis/sentinel.conf
redis-sentinel /etc/redis/sentinel.conf

Query Sentinel

查询Sentinel状态

redis-cli -p 26379 SENTINEL masters redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster redis-cli -p 26379 SENTINEL replicas mymaster
undefined
redis-cli -p 26379 SENTINEL masters redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster redis-cli -p 26379 SENTINEL replicas mymaster
undefined

Redis Cluster Mode

Redis集群模式

Cluster mode distributes data across multiple shards automatically.
bash
undefined
集群模式可自动将数据分布到多个分片。
bash
undefined

Create a 6-node cluster (3 masters + 3 replicas)

创建6节点集群(3主+3从)

redis-cli --cluster create
10.0.0.1:6379 10.0.0.2:6379 10.0.0.3:6379
10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379
--cluster-replicas 1 -a strong_redis_password
redis-cli --cluster create
10.0.0.1:6379 10.0.0.2:6379 10.0.0.3:6379
10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379
--cluster-replicas 1 -a strong_redis_password

Check cluster status

检查集群状态

redis-cli -c -a strong_redis_password CLUSTER INFO redis-cli -c -a strong_redis_password CLUSTER NODES
redis-cli -c -a strong_redis_password CLUSTER INFO redis-cli -c -a strong_redis_password CLUSTER NODES

Add a new node

添加新节点

redis-cli --cluster add-node 10.0.0.7:6379 10.0.0.1:6379
redis-cli --cluster add-node 10.0.0.7:6379 10.0.0.1:6379

Rebalance slots

重新平衡槽位

redis-cli --cluster rebalance 10.0.0.1:6379

```ini
redis-cli --cluster rebalance 10.0.0.1:6379

```ini

redis.conf for cluster nodes

集群节点的redis.conf配置

cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 5000
undefined
cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 5000
undefined

Common Patterns

常见模式

Caching with TTL

带TTL的缓存

bash
undefined
bash
undefined

Cache a database query result for 5 minutes

将数据库查询结果缓存5分钟

SET cache:user:42:profile '{"name":"Alice","plan":"pro"}' EX 300
SET cache:user:42:profile '{"name":"Alice","plan":"pro"}' EX 300

Cache-aside pattern (pseudocode):

缓存旁路模式(伪代码):

1. GET cache:key -> if hit, return

1. GET cache:key -> 如果命中则返回

2. Query database

2. 查询数据库

3. SET cache:key result EX 300

3. SET cache:key result EX 300

4. Return result

4. 返回结果

undefined
undefined

Rate Limiting (Sliding Window)

限流(滑动窗口)

bash
undefined
bash
undefined

Allow 100 requests per minute per user

每个用户每分钟允许100次请求

Using a sorted set with timestamps as scores

使用带时间戳作为分数的有序集合

ZADD ratelimit:user:42 1700000000.123 "req-uuid-1" ZREMRANGEBYSCORE ratelimit:user:42 0 1699999940.000 ZCARD ratelimit:user:42 EXPIRE ratelimit:user:42 60
ZADD ratelimit:user:42 1700000000.123 "req-uuid-1" ZREMRANGEBYSCORE ratelimit:user:42 0 1699999940.000 ZCARD ratelimit:user:42 EXPIRE ratelimit:user:42 60

If ZCARD >= 100, reject the request

如果ZCARD >= 100,则拒绝请求

undefined
undefined

Pub/Sub Messaging

发布/订阅消息

bash
undefined
bash
undefined

Terminal 1 — subscriber

终端1 —— 订阅者

redis-cli -a strong_redis_password SUBSCRIBE notifications:order-updates
redis-cli -a strong_redis_password SUBSCRIBE notifications:order-updates

Terminal 2 — publisher

终端2 —— 发布者

redis-cli -a strong_redis_password PUBLISH notifications:order-updates '{"orderId":42,"status":"shipped"}'
redis-cli -a strong_redis_password PUBLISH notifications:order-updates '{"orderId":42,"status":"shipped"}'

Pattern subscription

模式订阅

PSUBSCRIBE notifications:*
undefined
PSUBSCRIBE notifications:*
undefined

Distributed Locking (Redlock Pattern)

分布式锁(Redlock模式)

bash
undefined
bash
undefined

Acquire lock

获取锁

SET lock:resource:42 "worker-abc" NX EX 30
SET lock:resource:42 "worker-abc" NX EX 30

Returns OK if acquired, nil if already held

获取成功返回OK,已被占用则返回nil

Release lock (use Lua script to ensure atomicity)

释放锁(使用Lua脚本确保原子性)

redis-cli -a strong_redis_password EVAL " if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end " 1 lock:resource:42 "worker-abc"
undefined
redis-cli -a strong_redis_password EVAL " if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end " 1 lock:resource:42 "worker-abc"
undefined

Docker Compose Setup

Docker Compose配置

yaml
undefined
yaml
undefined

docker-compose.yml

docker-compose.yml

version: "3.9"
services: redis: image: redis:7-alpine restart: unless-stopped ports: - "6379:6379" volumes: - redis_data:/data - ./redis.conf:/usr/local/etc/redis/redis.conf:ro command: redis-server /usr/local/etc/redis/redis.conf healthcheck: test: ["CMD", "redis-cli", "-a", "strong_redis_password", "ping"] interval: 10s timeout: 5s retries: 5
redis-sentinel: image: redis:7-alpine restart: unless-stopped ports: - "26379:26379" volumes: - ./sentinel.conf:/usr/local/etc/redis/sentinel.conf command: redis-sentinel /usr/local/etc/redis/sentinel.conf depends_on: redis: condition: service_healthy
redis-commander: image: rediscommander/redis-commander:latest restart: unless-stopped ports: - "8081:8081" environment: REDIS_HOSTS: "local:redis:6379:0:strong_redis_password" depends_on: redis: condition: service_healthy
volumes: redis_data:

```bash
docker compose up -d
redis-cli -h 127.0.0.1 -a strong_redis_password ping
version: "3.9"
services: redis: image: redis:7-alpine restart: unless-stopped ports: - "6379:6379" volumes: - redis_data:/data - ./redis.conf:/usr/local/etc/redis/redis.conf:ro command: redis-server /usr/local/etc/redis/redis.conf healthcheck: test: ["CMD", "redis-cli", "-a", "strong_redis_password", "ping"] interval: 10s timeout: 5s retries: 5
redis-sentinel: image: redis:7-alpine restart: unless-stopped ports: - "26379:26379" volumes: - ./sentinel.conf:/usr/local/etc/redis/sentinel.conf command: redis-sentinel /usr/local/etc/redis/sentinel.conf depends_on: redis: condition: service_healthy
redis-commander: image: rediscommander/redis-commander:latest restart: unless-stopped ports: - "8081:8081" environment: REDIS_HOSTS: "local:redis:6379:0:strong_redis_password" depends_on: redis: condition: service_healthy
volumes: redis_data:

```bash
docker compose up -d
redis-cli -h 127.0.0.1 -a strong_redis_password ping

Monitoring

监控

bash
undefined
bash
undefined

Real-time stats

实时统计

redis-cli -a strong_redis_password INFO stats redis-cli -a strong_redis_password INFO memory redis-cli -a strong_redis_password INFO replication
redis-cli -a strong_redis_password INFO stats redis-cli -a strong_redis_password INFO memory redis-cli -a strong_redis_password INFO replication

Key metrics to watch

需要关注的关键指标

redis-cli -a strong_redis_password INFO stats | grep -E "keyspace_hits|keyspace_misses"
redis-cli -a strong_redis_password INFO stats | grep -E "keyspace_hits|keyspace_misses"

Hit ratio = hits / (hits + misses) — aim for > 95%

命中率 = hits / (hits + misses) —— 目标值>95%

Memory usage breakdown

内存使用明细

redis-cli -a strong_redis_password MEMORY STATS
redis-cli -a strong_redis_password MEMORY STATS

Slow log (queries > 10ms by default)

慢查询日志(默认记录耗时>10ms的查询)

redis-cli -a strong_redis_password SLOWLOG GET 10 redis-cli -a strong_redis_password SLOWLOG LEN
redis-cli -a strong_redis_password SLOWLOG GET 10 redis-cli -a strong_redis_password SLOWLOG LEN

Monitor all commands in real time (debugging only — impacts performance)

实时监控所有命令(仅用于调试——影响性能)

redis-cli -a strong_redis_password MONITOR
redis-cli -a strong_redis_password MONITOR

Connected clients

已连接客户端

redis-cli -a strong_redis_password CLIENT LIST
undefined
redis-cli -a strong_redis_password CLIENT LIST
undefined

Troubleshooting

故障排查

SymptomLikely CauseFix
OOM command not allowed
maxmemory
limit reached
Increase
maxmemory
or set a stricter eviction policy
High latency spikesRDB save or AOF rewrite forkingUse
save ""
to disable RDB if AOF is enabled; tune
auto-aof-rewrite-min-size
LOADING Redis is loading the dataset in memory
Large dataset being restored on startupWait for load to complete; consider smaller dataset or faster disk
Cache hit ratio < 90%TTLs too short or working set exceeds memoryIncrease
maxmemory
; review TTL strategy
Sentinel not failing overFewer than quorum Sentinels reachableEnsure >= 3 Sentinels are running and network-connected
CROSSSLOT
error in cluster
Multi-key command spans slotsUse hash tags
{user:42}:profile
to colocate related keys
症状可能原因解决方法
OOM command not allowed
已达到
maxmemory
限制
增大
maxmemory
值或设置更严格的淘汰策略
延迟峰值过高RDB保存或AOF重写时创建子进程若启用AOF则使用
save ""
禁用RDB;调整
auto-aof-rewrite-min-size
LOADING Redis is loading the dataset in memory
启动时正在恢复大型数据集等待加载完成;考虑缩小数据集或使用更快的磁盘
缓存命中率<90%TTL过短或工作集超出内存容量增大
maxmemory
;优化TTL策略
Sentinel未执行故障转移可用Sentinel数量未达到仲裁要求确保至少3个Sentinel运行且网络连通
集群中出现
CROSSSLOT
错误
多键命令跨槽位使用哈希标签
{user:42}:profile
将相关键放在同一槽位

Related Skills

相关技能

  • postgresql - Primary database that Redis caches
  • mysql - Primary database that Redis caches
  • mongodb - Document database that Redis can front
  • database-backups - Include RDB files in backup strategy
  • postgresql - Redis缓存的主数据库
  • mysql - Redis缓存的主数据库
  • mongodb - Redis可作为前置缓存的文档数据库
  • database-backups - 将RDB文件纳入备份策略