mcpField
R
redis

redis

github.com/bagelhole数据与数据库1.2k380 次安装23 周前更新
代码仓库

关于 redis

redis 是面向 Redis 配置、运维与优化的技能,适用于需要缓存、队列、限流和实时数据存储的开发与运维场景。内容涵盖数据结构操作、持久化、高可用、集群和监控。

主要功能

  1. 01Redis 安装与核心配置
  2. 02字符串、哈希、列表等操作
  3. 03配置 RDB 与 AOF 持久化
  4. 04设置 Sentinel 与集群模式
  5. 05实现缓存、限流和消息模式
  6. 06查看指标并排查常见故障

适用场景

  1. 01用 TTL 缓存数据库查询结果
  2. 02使用列表构建任务队列
  3. 03通过 Sentinel 配置自动故障转移
  4. 04监控内存、命中率和复制状态

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill redis

安装后在 Claude Code 中输入/redis确认已加载。

详细介绍

Redis

配置、运行和优化 Redis,用于缓存、队列、速率限制和实时数据存储。

使用场景

  • 需要低延迟的内存缓存来减轻数据库负载。
  • 应用需要速率限制、会话存储或排行榜。
  • 需要在服务之间进行发布/订阅消息传递。
  • 希望使用内存存储来支持分布式锁或作业队列。

前置条件

  • Linux 服务器或 Docker。
  • 安装软件包需要 root 或 sudo 权限。
  • 生产环境建议使用 Redis 7.x。

安装和设置

# Debian / Ubuntu
sudo apt update
sudo apt install -y redis-server

# RHEL / Amazon Linux
sudo dnf install -y redis

# Start and enable
sudo systemctl enable --now redis-server

# Verify
redis-cli ping
# Expected output: PONG

核心配置

编辑 /etc/redis/redis.conf:

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

# Memory
maxmemory 2gb
maxmemory-policy allkeys-lru

# Connections
maxclients 10000
timeout 300
tcp-keepalive 60

# Logging
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 ""
sudo systemctl restart redis-server

redis-cli 命令参考

# Connect with authentication
redis-cli -a strong_redis_password

# Connect to a remote host
redis-cli -h 10.0.0.5 -p 6379 -a strong_redis_password
字符串操作
SET user:1:name "Alice"
GET user:1:name

# Set with TTL (seconds)
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

# Increment counters
INCR page:views:/home
INCRBY api:quota:user:1 -1
哈希操作
HSET user:1 name "Alice" email "[email protected]" plan "pro"
HGET user:1 email
HGETALL user:1
HINCRBY user:1 login_count 1
列表操作(队列)
LPUSH queue:emails '{"to":"[email protected]","subject":"Welcome"}'
RPOP queue:emails
LLEN queue:emails

# Blocking pop (worker pattern)
BRPOP queue:emails 30
集合和有序集合操作
# Sets — unique tags
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"
键管理
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

持久化

RDB 快照
# redis.conf — save snapshots at intervals
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
AOF(仅追加文件)
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec    # good balance of safety and performance
# Options: always (safest, slowest), everysec (recommended), no (OS decides)

# AOF rewrite thresholds
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
推荐的生产环境策略

同时使用 RDB 和 AOF。RDB 可实现快速重启并生成紧凑的备份。AOF 可将数据持久性精确到 1 秒粒度。

save 900 1
save 300 10
appendonly yes
appendfsync everysec

Redis Sentinel(高可用性)

Sentinel 会监控 Redis 实例并执行自动故障转移。

Sentinel 配置
# /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

至少运行 3 个 Sentinel 实例以满足法定人数要求。

# Start Sentinel
redis-sentinel /etc/redis/sentinel.conf

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

Redis 集群模式

集群模式会自动将数据分布到多个分片中。

# Create a 6-node cluster (3 masters + 3 replicas)
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

# Add a new node
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
# redis.conf for cluster nodes
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000

常见模式

带 TTL 的缓存
# Cache a database query result for 5 minutes
SET cache:user:42:profile '{"name":"Alice","plan":"pro"}' EX 300

# Cache-aside pattern (pseudocode):
# 1. GET cache:key -> if hit, return
# 2. Query database
# 3. SET cache:key result EX 300
# 4. Return result
速率限制(滑动窗口)
# Allow 100 requests per minute per user
# 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
# If ZCARD >= 100, reject the request
发布/订阅消息传递
# Terminal 1 — subscriber
redis-cli -a strong_redis_password
SUBSCRIBE notifications:order-updates

# Terminal 2 — publisher
redis-cli -a strong_redis_password
PUBLISH notifications:order-updates '{"orderId":42,"status":"shipped"}'

# Pattern subscription
PSUBSCRIBE notifications:*
分布式锁(Redlock 模式)
# Acquire lock
SET lock:resource:42 "worker-abc" NX EX 30
# Returns OK if acquired, nil if already held

# Release lock (use Lua script to ensure atomicity)
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"

Docker Compose 设置

# 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:
docker compose up -d
redis-cli -h 127.0.0.1 -a strong_redis_password ping

监控

# 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

# Key metrics to watch
redis-cli -a strong_redis_password INFO stats | grep -E "keyspace_hits|keyspace_misses"
# Hit ratio = hits / (hits + misses) — aim for > 95%

# Memory usage breakdown
redis-cli -a strong_redis_password MEMORY STATS

# Slow log (queries > 10ms by default)
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

# Connected clients
redis-cli -a strong_redis_password CLIENT LIST

故障排查

症状可能原因解决方法
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,将相关键放在同一位置

相关技能

评论

支持 Markdown