跳到导航

消息格式

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

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

asyncapi.yml
components:
messages:
UserEvent:
name: UserEvent
title: User Event Message
summary: Event triggered by user actions
contentType: application/json
payload:
$ref: '#/components/schemas/UserEventPayload'
headers:
$ref: '#/components/schemas/MessageHeaders'

消息负载

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

asyncapi.yml
components:
messages:
OrderCreated:
contentType: application/json
payload:
$ref: '#/components/schemas/Order'
schemas:
Order:
type: object
properties:
id:
type: string
format: uuid
description: Unique order identifier
customerId:
type: string
description: Customer who placed the order
items:
type: array
items:
$ref: '#/components/schemas/OrderItem'
total:
type: number
format: decimal
description: Total order amount
createdAt:
type: string
format: date-time
description: When the order was created
required:
- id
- customerId
- items
- total

消息头

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

asyncapi.yml
components:
messages:
NotificationEvent:
contentType: application/json
payload:
$ref: '#/components/schemas/Notification'
headers:
$ref: '#/components/schemas/NotificationHeaders'
schemas:
NotificationHeaders:
type: object
properties:
messageId:
type: string
description: Unique message identifier
timestamp:
type: string
format: date-time
description: Message timestamp
source:
type: string
description: Source service that generated the message
priority:
type: string
enum: [low, medium, high, urgent]
description: Message priority level

内容类型

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

asyncapi.yml
components:
messages:
JsonMessage:
contentType: application/json
payload:
$ref: '#/components/schemas/JsonPayload'
BinaryMessage:
contentType: application/octet-stream
payload:
type: string
format: binary
TextMessage:
contentType: text/plain
payload:
type: string

消息示例

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

asyncapi.yml
components:
messages:
UserSignup:
name: UserSignup
title: User Signup Event
contentType: application/json
payload:
$ref: '#/components/schemas/User'
examples:
- name: StandardSignup
summary: Regular user signup
payload:
id: "123e4567-e89b-12d3-a456-426614174000"
email: "john@example.com"
name: "John Doe"
signupSource: "web"
createdAt: "2024-01-15T10:30:00Z"

消息特性

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

asyncapi.yml
components:
messageTraits:
commonHeaders:
headers:
type: object
properties:
messageId:
type: string
timestamp:
type: string
format: date-time
messages:
UserEvent:
traits:
- $ref: '#/components/messageTraits/commonHeaders'
contentType: application/json
payload:
$ref: '#/components/schemas/UserEventPayload'

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