两者都是 Redis 批量操作的方式,但在 实现原理 和 适用场景 上有很大不同。
1. pipeline
(流水线)
概念
Redis Pipeline 允许在 单个请求中发送多个命令,减少网络 I/O 开销,提高性能。
它适用于批量写入或读取场景。
特点
多个命令一起发送,但执行顺序不变。
减少 TCP 往返次数(N 个请求变成 1 次)。
适用于批量写入、批量读取、事务提交。
示例
import redis
r = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
# 开启 pipeline
pipe = r.pipeline()
# 添加多个命令
pipe.set("key1", "value1")
pipe.set("key2", "value2")
pipe.get("key1")
pipe.get("key2")
# 一次性执行所有命令
results = pipe.execute()
print(results) # [True, True, 'value1', 'value2']
执行流程
set key1 value1
set key2 value2
get key1
get key2
一次性发送到 Redis 服务器
Redis 依次执行
返回所有结果
2. MGET
(批量获取)
概念
MGET
是 Redis 提供的 原生批量查询 命令,可以一次性获取多个 key 的值。
特点
只能用于
GET
操作(批量读取)。底层执行是一个 Redis 命令,因此比
pipeline
更高效。Redis 服务器端一次性执行
MGET
并返回结果,减少 CPU 开销。
示例
import redis
r = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
# 批量获取多个 key
results = r.mget(["key1", "key2"])
print(results) # ['value1', 'value2']
执行流程
MGET key1 key2
Redis 一次性查询多个 key
一次性返回所有结果
3. pipeline
vs MGET
对比
4. 适用场景
适合 pipeline
批量写入(如
SET key1 value1
、SET key2 value2
)。组合操作(如
SET + GET
或INCR + EXPIRE
)。事务操作(如
MULTI/EXEC
)。批量删除、过期处理。
适合 MGET
仅批量查询 key,如:
获取多个用户信息:
MGET user:1 user:2 user:3
读取缓存数据(如 Redis 作为缓存层)
5. 结论
如果只是批量读取,用
MGET
更快。如果需要批量执行多个不同命令(读写混合),用
pipeline
更灵活。
简单记忆
MGET
更高效,但只能GET
。pipeline
适用于读写混合,减少网络开销。