Redis Stream
Stream 是可靠的追加日志,做消息队列与事件溯源。
Key PointsStream 比 List/Pub-Sub 更可靠:持久化、消费组、未确认消息重投。
生产与消费
Shell
XADD orders * product "book" qty 2 # * 让服务端生成 id
XREAD COUNT 2 STREAMS orders 0 # 从开头读 2 条Output
1) "orders"
2) 1) 1) "1700000000000-0"
2) 1) "product"
2) "book"
3) "qty"
4) "2"消费组(可靠队列)
Shell
XGROUP CREATE orders cg1 0 MKSTREAM
XREADGROUP GROUP cg1 c1 COUNT 1 STREAMS orders >
XACK orders cg1 1700000000000-0 # 确认消费成功Stream is Redis's most 'real queue' structure: persisted messages, consumer groups, and redelivery of un-ACKed items via XPENDING. Great for order streams, event sourcing, or a light MQ.
生产与消费
Shell
XADD orders * product "book" qty 2 # * 让服务端生成 id
XREAD COUNT 2 STREAMS orders 0 # 从开头读 2 条Output
1) "orders"
2) 1) 1) "1700000000000-0"
2) 1) "product"
2) "book"
3) "qty"
4) "2"消费组(可靠队列)
Shell
XGROUP CREATE orders cg1 0 MKSTREAM
XREADGROUP GROUP cg1 c1 COUNT 1 STREAMS orders >
XACK orders cg1 1700000000000-0 # 确认消费成功Stream 是 Redis 里最接近「正经消息队列」的结构:消息持久化、多消费者组、未 ACK 的可重投(
XPENDING 查看)。做订单流水、事件溯源、或替代轻量 MQ 都很合适。