Redis Stream

Stream 是可靠的追加日志,做消息队列与事件溯源。

Beginner
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.

Friends & Partners