Redis

Connection & Server

redis-cli                              # connect to localhost:6379
redis-cli -h 10.0.0.1 -p 6380 -a secret  # connect with auth
redis-cli -u redis://user:pass@host:6379/0  # URI connection
redis-cli -n 2                         # connect to database 2

PING                                    # test connection → PONG
INFO                                    # server info
INFO memory                             # memory stats
INFO replication                        # replication stats
DBSIZE                                  # number of keys in current DB
SELECT 1                                # switch to database 1
FLUSHDB                                 # delete all keys in current DB
FLUSHALL                                # delete all keys in all DBs

String

SET name "Alice"                        # set key
GET name                                # get value → "Alice"
SETNX key "value"                       # set only if not exists
SETEX session 3600 "data"               # set with 3600s TTL
MSET k1 "v1" k2 "v2" k3 "v3"           # set multiple keys
MGET k1 k2 k3                           # get multiple values
INCR counter                             # increment (+1)
INCRBY counter 10                        # increment by 10
DECR counter                             # decrement (-1)
INCRBYFLOAT price 2.5                    # increment float
APPEND name " Smith"                     # append to string
STRLEN name                              # string length
GETRANGE name 0 4                        # substring

Hash

HSET user:1 name "Alice" age 25 email "a@b.com"   # set fields
HGET user:1 name                        # get single field → "Alice"
HMGET user:1 name age                   # get multiple fields
HGETALL user:1                          # get all fields and values
HDEL user:1 email                       # delete field
HEXISTS user:1 name                     # check field exists → 1
HKEYS user:1                            # all field names
HVALS user:1                            # all field values
HLEN user:1                             # number of fields
HINCRBY user:1 age 1                    # increment field by 1
HSETNX user:1 role "admin"              # set field only if not exists

List

LPUSH tasks "task3" "task2" "task1"     # push to head (left)
RPUSH tasks "task4" "task5"             # push to tail (right)
LPOP tasks                              # pop from head
RPOP tasks                              # pop from tail
LLEN tasks                              # list length
LRANGE tasks 0 -1                       # get all elements
LRANGE tasks 0 2                        # get first 3 elements
LINDEX tasks 0                          # get by index
LSET tasks 0 "updated"                  # set by index
LREM tasks 2 "task1"                    # remove 2 occurrences
LTRIM tasks 0 99                        # keep only first 100 elements
BLPOP queue 30                          # blocking pop (timeout 30s)

Set

SADD tags "redis" "db" "cache"          # add members
SMEMBERS tags                           # get all members
SISMEMBER tags "redis"                  # check membership → 1
SCARD tags                              # member count
SREM tags "cache"                       # remove member
SPOP tags                               # remove and return random member
SRANDMEMBER tags 2                      # get 2 random members

SUNION set1 set2                        # union
SINTER set1 set2                        # intersection
SDIFF set1 set2                         # difference
SUNIONSTORE result set1 set2            # union → store in result

Sorted Set

ZADD leaderboard 100 "Alice" 95 "Bob" 88 "Charlie"   # add with scores
ZSCORE leaderboard "Alice"              # get score → "100"
ZRANK leaderboard "Alice"               # rank (ascending, 0-based)
ZREVRANK leaderboard "Alice"            # rank (descending)
ZRANGE leaderboard 0 -1                 # ascending by score
ZRANGE leaderboard 0 -1 WITHSCORES     # with scores
ZREVRANGE leaderboard 0 2 WITHSCORES   # top 3 descending
ZINCRBY leaderboard 5 "Bob"             # increment score by 5
ZCARD leaderboard                       # member count
ZCOUNT leaderboard 80 100               # count members with score 80-100
ZRANGEBYSCORE leaderboard 90 +INF      # score >= 90
ZREM leaderboard "Charlie"              # remove member
ZREMRANGEBYRANK leaderboard 0 2         # remove by rank range

Key Management

EXISTS key                              # check if key exists → 1
DEL key1 key2                           # delete keys
UNLINK key1 key2                        # async delete (non-blocking)
TYPE key                                # key data type
RENAME old_key new_key                  # rename key
TTL key                                 # remaining TTL in seconds (-1=none, -2=gone)
PTTL key                                # TTL in milliseconds
EXPIRE key 3600                         # set TTL to 3600 seconds
PERSIST key                             # remove TTL (make persistent)

SCAN 0 COUNT 100                        # iterate keys (cursor-based)
SCAN 0 MATCH user:* COUNT 100           # iterate with pattern
RANDOMKEY                               # return random key

Pub/Sub

SUBSCRIBE channel1 channel2             # subscribe to channels
PSUBSCRIBE news:*                       # subscribe with pattern
UNSUBSCRIBE channel1                    # unsubscribe
PUBLISH channel1 "hello world"          # publish message
PUBSUB CHANNELS                         # list active channels
PUBSUB NUMSUB channel1                  # subscriber count

Transactions & Lua

MULTI                                   # begin transaction
SET account:A 500
SET account:B 300
EXEC                                    # execute all commands

DISCARD                                 # cancel transaction
WATCH key                               # watch key for changes (optimistic lock)
UNWATCH                                 # unwatch all keys
# Lua script (atomic execution)
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey myvalue
EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# script cache
SCRIPT LOAD "return 1"                  # load and cache script
EVALSHA <sha1> 0                        # execute cached script

Persistence

# RDB snapshot
SAVE                                    # synchronous save (blocks)
BGSAVE                                  # background save
LASTSAVE                                # timestamp of last save
CONFIG GET save                         # RDB schedule rules

# AOF append-only file
CONFIG GET appendonly                   # check AOF status
CONFIG SET appendonly yes               # enable AOF
CONFIG GET appendfsync                  # AOF sync policy
# everysec   - sync every second (recommended)
# always     - sync every write (safest, slowest)
# no         - let OS decide (fastest)

BGREWRITEAOF                            # compact AOF file

Replication

INFO replication                        # replication status
ROLE                                    # master or slave

# on replica
REPLICAOF host 6379                     # become replica of host
REPLICAOF NO ONE                        # promote to master

# config for replica
# replicaof 10.0.0.1 6379
# masterauth secret

Performance & Debug

SLOWLOG GET 10                          # last 10 slow queries
SLOWLOG LEN                             # slow log count
CONFIG SET slowlog-log-slower-than 10000  # log queries > 10ms

CLIENT LIST                             # connected clients
CLIENT KILL ADDR 10.0.0.1:12345        # kill client connection
MONITOR                                 # stream all commands (debug only!)

MEMORY USAGE key                        # memory used by key
MEMORY DOCTOR                           # memory analysis tips

# benchmark
redis-benchmark -t set,get -n 100000    # benchmark SET/GET, 100k requests
redis-benchmark -t ping -c 50           # 50 parallel connections

连接与服务器

redis-cli                              # 连接 localhost:6379
redis-cli -h 10.0.0.1 -p 6380 -a secret  # 指定地址和密码连接
redis-cli -u redis://user:pass@host:6379/0  # URI 方式连接
redis-cli -n 2                         # 连接到数据库 2

PING                                    # 测试连接 → PONG
INFO                                    # 服务器信息
INFO memory                             # 内存统计
INFO replication                        # 复制状态
DBSIZE                                  # 当前数据库键数量
SELECT 1                                # 切换到数据库 1
FLUSHDB                                 # 清空当前数据库
FLUSHALL                                # 清空所有数据库

字符串 (String)

SET name "Alice"                        # 设置键值
GET name                                # 获取值 → "Alice"
SETNX key "value"                       # 仅在不存在时设置
SETEX session 3600 "data"               # 设置并指定 3600 秒过期
MSET k1 "v1" k2 "v2" k3 "v3"           # 批量设置
MGET k1 k2 k3                           # 批量获取
INCR counter                             # 自增 (+1)
INCRBY counter 10                        # 自增指定值
DECR counter                             # 自减 (-1)
INCRBYFLOAT price 2.5                    # 浮点数自增
APPEND name " Smith"                     # 追加字符串
STRLEN name                              # 字符串长度
GETRANGE name 0 4                        # 截取子串

哈希 (Hash)

HSET user:1 name "Alice" age 25 email "a@b.com"   # 设置多个字段
HGET user:1 name                        # 获取单个字段 → "Alice"
HMGET user:1 name age                   # 获取多个字段
HGETALL user:1                          # 获取所有字段和值
HDEL user:1 email                       # 删除字段
HEXISTS user:1 name                     # 字段是否存在 → 1
HKEYS user:1                            # 所有字段名
HVALS user:1                            # 所有字段值
HLEN user:1                             # 字段数量
HINCRBY user:1 age 1                    # 字段自增
HSETNX user:1 role "admin"              # 仅在字段不存在时设置

列表 (List)

LPUSH tasks "task3" "task2" "task1"     # 从头部插入
RPUSH tasks "task4" "task5"             # 从尾部插入
LPOP tasks                              # 从头部弹出
RPOP tasks                              # 从尾部弹出
LLEN tasks                              # 列表长度
LRANGE tasks 0 -1                       # 获取所有元素
LRANGE tasks 0 2                        # 获取前 3 个元素
LINDEX tasks 0                          # 按索引获取
LSET tasks 0 "updated"                  # 按索引修改
LREM tasks 2 "task1"                    # 移除 2 个指定值
LTRIM tasks 0 99                        # 只保留前 100 个元素
BLPOP queue 30                          # 阻塞式弹出(超时 30 秒)

集合 (Set)

SADD tags "redis" "db" "cache"          # 添加成员
SMEMBERS tags                           # 获取所有成员
SISMEMBER tags "redis"                  # 检查是否成员 → 1
SCARD tags                              # 成员数量
SREM tags "cache"                       # 移除成员
SPOP tags                               # 随机弹出成员
SRANDMEMBER tags 2                      # 随机获取 2 个成员

SUNION set1 set2                        # 并集
SINTER set1 set2                        # 交集
SDIFF set1 set2                         # 差集
SUNIONSTORE result set1 set2            # 并集存入 result

有序集合 (Sorted Set)

ZADD leaderboard 100 "Alice" 95 "Bob" 88 "Charlie"   # 添加带分数的成员
ZSCORE leaderboard "Alice"              # 获取分数 → "100"
ZRANK leaderboard "Alice"               # 排名(升序,从 0 开始)
ZREVRANK leaderboard "Alice"            # 排名(降序)
ZRANGE leaderboard 0 -1                 # 按分数升序
ZRANGE leaderboard 0 -1 WITHSCORES     # 带分数
ZREVRANGE leaderboard 0 2 WITHSCORES   # 前 3 名降序
ZINCRBY leaderboard 5 "Bob"             # 分数加 5
ZCARD leaderboard                       # 成员数量
ZCOUNT leaderboard 80 100               # 分数 80-100 的成员数
ZRANGEBYSCORE leaderboard 90 +INF      # 分数 >= 90
ZREM leaderboard "Charlie"              # 移除成员
ZREMRANGEBYRANK leaderboard 0 2         # 按排名范围移除

键管理

EXISTS key                              # 键是否存在 → 1
DEL key1 key2                           # 删除键
UNLINK key1 key2                        # 异步删除(非阻塞)
TYPE key                                # 键的数据类型
RENAME old_key new_key                  # 重命名键
TTL key                                 # 剩余过期秒数 (-1=永不过期, -2=已不存在)
PTTL key                                # 剩余过期毫秒数
EXPIRE key 3600                         # 设置 3600 秒后过期
PERSIST key                             # 移除过期时间(持久化)

SCAN 0 COUNT 100                        # 游标式遍历键
SCAN 0 MATCH user:* COUNT 100           # 按模式遍历
RANDOMKEY                               # 随机返回一个键

发布订阅 (Pub/Sub)

SUBSCRIBE channel1 channel2             # 订阅频道
PSUBSCRIBE news:*                       # 模式订阅
UNSUBSCRIBE channel1                    # 取消订阅
PUBLISH channel1 "hello world"          # 发布消息
PUBSUB CHANNELS                         # 列出活跃频道
PUBSUB NUMSUB channel1                  # 订阅者数量

事务与 Lua

MULTI                                   # 开启事务
SET account:A 500
SET account:B 300
EXEC                                    # 执行所有命令

DISCARD                                 # 取消事务
WATCH key                               # 监视键(乐观锁)
UNWATCH                                 # 取消监视
# Lua 脚本(原子执行)
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey myvalue
EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# 脚本缓存
SCRIPT LOAD "return 1"                  # 加载并缓存脚本
EVALSHA <sha1> 0                        # 执行缓存脚本

持久化

# RDB 快照
SAVE                                    # 同步保存(阻塞)
BGSAVE                                  # 后台保存
LASTSAVE                                # 上次保存时间戳
CONFIG GET save                         # RDB 保存策略

# AOF 追加文件
CONFIG GET appendonly                   # 查看 AOF 状态
CONFIG SET appendonly yes               # 开启 AOF
CONFIG GET appendfsync                  # AOF 同步策略
# everysec   - 每秒同步(推荐)
# always     - 每次写入同步(最安全,最慢)
# no         - 由操作系统决定(最快)

BGREWRITEAOF                            # 压缩 AOF 文件

主从复制

INFO replication                        # 复制状态
ROLE                                    # master 或 slave

# 在从节点执行
REPLICAOF host 6379                     # 成为 host 的从节点
REPLICAOF NO ONE                        # 提升为主节点

# 从节点配置
# replicaof 10.0.0.1 6379
# masterauth secret

性能与调试

SLOWLOG GET 10                          # 最近 10 条慢查询
SLOWLOG LEN                             # 慢查询数量
CONFIG SET slowlog-log-slower-than 10000  # 记录超过 10ms 的查询

CLIENT LIST                             # 已连接的客户端
CLIENT KILL ADDR 10.0.0.1:12345        # 断开客户端连接
MONITOR                                 # 实时监控所有命令(仅调试用!)

MEMORY USAGE key                        # 键占用的内存
MEMORY DOCTOR                           # 内存分析建议

# 基准测试
redis-benchmark -t set,get -n 100000    # 测试 SET/GET,10 万次请求
redis-benchmark -t ping -c 50           # 50 个并发连接