消息格式
为事件驱动通信定义消息模式、内容类型和结构
AsyncAPI 中的消息在 components.messages 部分定义,并从频道和操作中引用。它们定义了通过事件驱动 API 交换的数据的结构和格式。
asyncapi.yml
components:messages:UserEvent:name: UserEventtitle: User Event Messagesummary: Event triggered by user actionscontentType: application/jsonpayload:$ref: '#/components/schemas/UserEventPayload'headers:$ref: '#/components/schemas/MessageHeaders'
消息负载
负载定义了消息数据的结构:
asyncapi.yml
components:messages:OrderCreated:contentType: application/jsonpayload:$ref: '#/components/schemas/Order'schemas:Order:type: objectproperties:id:type: stringformat: uuiddescription: Unique order identifiercustomerId:type: stringdescription: Customer who placed the orderitems:type: arrayitems:$ref: '#/components/schemas/OrderItem'total:type: numberformat: decimaldescription: Total order amountcreatedAt:type: stringformat: date-timedescription: When the order was createdrequired:- id- customerId- items- total
消息头
您可以定义与消息一起发送的头:
asyncapi.yml
components:messages:NotificationEvent:contentType: application/jsonpayload:$ref: '#/components/schemas/Notification'headers:$ref: '#/components/schemas/NotificationHeaders'schemas:NotificationHeaders:type: objectproperties:messageId:type: stringdescription: Unique message identifiertimestamp:type: stringformat: date-timedescription: Message timestampsource:type: stringdescription: Source service that generated the messagepriority:type: stringenum: [low, medium, high, urgent]description: Message priority level
内容类型
AsyncAPI 支持各种消息内容类型:
asyncapi.yml
components:messages:JsonMessage:contentType: application/jsonpayload:$ref: '#/components/schemas/JsonPayload'BinaryMessage:contentType: application/octet-streampayload:type: stringformat: binaryTextMessage:contentType: text/plainpayload:type: string
消息示例
提供具体示例以帮助开发者理解您的消息格式:
asyncapi.yml
components:messages:UserSignup:name: UserSignuptitle: User Signup EventcontentType: application/jsonpayload:$ref: '#/components/schemas/User'examples:- name: StandardSignupsummary: Regular user signuppayload: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: objectproperties:messageId:type: stringtimestamp:type: stringformat: date-timemessages:UserEvent:traits:- $ref: '#/components/messageTraits/commonHeaders'contentType: application/jsonpayload:$ref: '#/components/schemas/UserEventPayload'
这种方法有助于在消息定义中保持一致性,同时减少重复。