消息格式

为事件驱动通信定义消息模式、内容类型和结构

以 Markdown 格式查看

AsyncAPI 中的消息在 components.messages 部分定义,并从频道和操作中引用。它们定义了通过事件驱动 API 交换的数据的结构和格式。

asyncapi.yml
1components:
2 messages:
3 UserEvent:
4 name: UserEvent
5 title: User Event Message
6 summary: Event triggered by user actions
7 contentType: application/json
8 payload:
9 $ref: '#/components/schemas/UserEventPayload'
10 headers:
11 $ref: '#/components/schemas/MessageHeaders'

消息负载

负载定义了消息数据的结构:

asyncapi.yml
1components:
2 messages:
3 OrderCreated:
4 contentType: application/json
5 payload:
6 $ref: '#/components/schemas/Order'
7 schemas:
8 Order:
9 type: object
10 properties:
11 id:
12 type: string
13 format: uuid
14 description: Unique order identifier
15 customerId:
16 type: string
17 description: Customer who placed the order
18 items:
19 type: array
20 items:
21 $ref: '#/components/schemas/OrderItem'
22 total:
23 type: number
24 format: decimal
25 description: Total order amount
26 createdAt:
27 type: string
28 format: date-time
29 description: When the order was created
30 required:
31 - id
32 - customerId
33 - items
34 - total

消息头

您可以定义与消息一起发送的头:

asyncapi.yml
1components:
2 messages:
3 NotificationEvent:
4 contentType: application/json
5 payload:
6 $ref: '#/components/schemas/Notification'
7 headers:
8 $ref: '#/components/schemas/NotificationHeaders'
9 schemas:
10 NotificationHeaders:
11 type: object
12 properties:
13 messageId:
14 type: string
15 description: Unique message identifier
16 timestamp:
17 type: string
18 format: date-time
19 description: Message timestamp
20 source:
21 type: string
22 description: Source service that generated the message
23 priority:
24 type: string
25 enum: [low, medium, high, urgent]
26 description: Message priority level

内容类型

AsyncAPI 支持各种消息内容类型:

asyncapi.yml
1components:
2 messages:
3 JsonMessage:
4 contentType: application/json
5 payload:
6 $ref: '#/components/schemas/JsonPayload'
7
8 BinaryMessage:
9 contentType: application/octet-stream
10 payload:
11 type: string
12 format: binary
13
14 TextMessage:
15 contentType: text/plain
16 payload:
17 type: string

消息示例

提供具体示例以帮助开发者理解您的消息格式:

asyncapi.yml
1components:
2 messages:
3 UserSignup:
4 name: UserSignup
5 title: User Signup Event
6 contentType: application/json
7 payload:
8 $ref: '#/components/schemas/User'
9 examples:
10 - name: StandardSignup
11 summary: Regular user signup
12 payload:
13 id: "123e4567-e89b-12d3-a456-426614174000"
14 email: "john@example.com"
15 name: "John Doe"
16 signupSource: "web"
17 createdAt: "2024-01-15T10:30:00Z"

消息特性

使用特性在多个消息之间共享通用消息属性:

asyncapi.yml
1components:
2 messageTraits:
3 commonHeaders:
4 headers:
5 type: object
6 properties:
7 messageId:
8 type: string
9 timestamp:
10 type: string
11 format: date-time
12
13 messages:
14 UserEvent:
15 traits:
16 - $ref: '#/components/messageTraits/commonHeaders'
17 contentType: application/json
18 payload:
19 $ref: '#/components/schemas/UserEventPayload'

这种方法有助于在消息定义中保持一致性,同时减少重复。