发布/订阅操作
AsyncAPI 中的操作定义在 operations 键下,通道定义在 channels 键下。以下是定义发布和订阅操作的示例:
asyncapi.yml
channels:user/notifications:address: user/notificationsmessages:UserNotification:$ref: '#/components/messages/UserNotification'operations:onUserNotification:action: receivechannel:$ref: '#/channels/user~1notifications'summary: Receive user notificationsdescription: Subscribe to user notification eventssendUserNotification:action: sendchannel:$ref: '#/channels/user~1notifications'summary: Send user notificationdescription: Publish a user notification event
消息示例
您可以通过在消息定义中使用 examples 键来提供消息示例:
asyncapi.yml
components:messages:UserNotification:name: UserNotificationtitle: User Notificationsummary: Notification sent to a usercontentType: application/jsonpayload:$ref: '#/components/schemas/Notification'examples:- name: EmailNotificationsummary: Example email notificationpayload:userId: "123e4567-e89b-12d3-a456-426614174000"type: "email"message: "Welcome to our service!"priority: "medium"
发布操作
发布操作表示您的服务发送到通道的消息:
asyncapi.yml
operations:publishOrderStatus:action: sendchannel:$ref: '#/channels/order~1status'summary: Publish order status updatedescription: Send order status updates to subscribersmessage:$ref: '#/components/messages/OrderStatus'
订阅操作
订阅操作表示您的服务从通道接收的消息:
asyncapi.yml
operations:subscribeToUserSignups:action: receivechannel:$ref: '#/channels/user~1signup'summary: Subscribe to user signupsdescription: Receive notifications when users sign upmessage:$ref: '#/components/messages/UserSignup'
双向通信
您可以为同一个通道定义发布和订阅操作,以启用双向通信:
asyncapi.yml
operations:sendChatMessage:action: sendchannel:$ref: '#/channels/chat~1room'summary: Send chat messagedescription: Send a message to a chat roomreceiveChatMessage:action: receivechannel:$ref: '#/channels/chat~1room'summary: Receive chat messagedescription: Receive messages from a chat room