RabbitMQ 之 Message
摘要
-
本文介绍 RabbitMQ 的 Message 的基本概念和用法。
-
本文使用的 RabbitMQ 版本为 4.1.4。
Message(消息) 是什么?
-
在 RabbitMQ 中,Message(消息)是消息队列中的数据单元。消息包含消息内容、消息属性等信息。
-
Message 组成:
-
- 消息内容:消息的内容,可以是任意数据。
-
- 消息属性:消息的属性,如消息的过期时间、消息的优先级、消息的标签等。
-
Publish message
-
Payload:消息的内容,可以是任意数据。
-
Payload encoding:消息内容的编码方式,
String
或者Base64
,默认为String
。 -
Delivery mode:消息的持久化模式,1 表示非持久化,2 表示持久化。
-
Headers:消息的头信息,用于与
Headers Exchange(头部交换机)
中的配置进行匹配。 -
Properties:消息的属性,如消息的过期时间、消息的优先级、消息的标签等。
属性名 | 中文含义 | 数据类型 | 默认值 | 典型用途 |
---|---|---|---|---|
content_type | 内容类型 | String | null | 指定消息的 MIME 类型,如 "text/plain" 、"application/json" |
content_encoding | 内容编码 | String | null | 指定消息内容的编码方式,如 "gzip" |
priority | 消息优先级 | Integer (0-255) | 0 | 结合 x-max-priority 控制消息处理顺序,数值越大优先级越高 |
correlation_id | 关联 ID | String | null | RPC 模式中关联请求与响应 |
reply_to | 回复队列名 | String | null | RPC 模式中指定响应消息的返回队列 |
expiration | 消息过期时间 | String (ms) | null | 消息的 TTL,毫秒为单位,过期后将被丢弃或进入死信队列 |
message_id | 消息 ID | String | null | 唯一标识一条消息,通常由生产者指定 |
timestamp | 时间戳 | Date / Long | null | 消息发送时间,通常是 Unix 时间戳 |
type | 消息类型 | String | null | 描述消息类型,如 "order" 或 "event" |
user_id | 用户 ID | String | null | 标识发送消息的用户,通常用于安全或审计 |
app_id | 应用 ID | String | null | 标识发送消息的应用程序 |
cluster_id | 集群 ID | String | null | RabbitMQ 集群 ID,实际中很少使用 |
-
与队列重叠的属性:
参数名称 | 队列参数(Queue Arguments) | 消息属性(Message Properties) | 谁的优先级更高 / 生效方式 |
---|---|---|---|
priority / x-max-priority | x-max-priority : 定义队列支持的最大优先级值 |
priority : 为单个消息设置优先级 |
队列先定义范围,消息只能在这个范围内取值 若 priority > x-max-priority ,则以x-max-priority 为准 |
expiration / x-message-ttl | x-message-ttl : 队列级别的消息统一 TTL |
expiration : 为单个消息设置 TTL(毫秒) |
如果同时设置,较短的 TTL 会生效 |
Get message
-
Ack Mode:消息确认模式
- Nack message requeue true: 确认失败,消息重新入队
- Automatic ack: 自动确认
- Reject requeue true: 拒绝,消息重新入队
- Reject requeue false: 拒绝,消息不重新入队
-
Encoding:消息内容编码方式
Auto String / Base64
,默认。如果消息载荷可以解释为UTF-8编码的字符串,就是String
,否则就是Base64
。Base64
。
-
Messages: 一次获取消息数量,默认为 1。