发布/订阅操作
发布/订阅操作
AsyncAPI 中的操作定义在 operations 键下,通道定义在 channels 键下。以下是定义发布和订阅操作的示例:
asyncapi.yml
1 channels: 2 user/notifications: 3 address: user/notifications 4 messages: 5 UserNotification: 6 $ref: '#/components/messages/UserNotification' 7 8 operations: 9 onUserNotification: 10 action: receive 11 channel: 12 $ref: '#/channels/user~1notifications' 13 summary: Receive user notifications 14 description: Subscribe to user notification events 15 sendUserNotification: 16 action: send 17 channel: 18 $ref: '#/channels/user~1notifications' 19 summary: Send user notification 20 description: Publish a user notification event
消息示例
您可以通过在消息定义中使用 examples 键来提供消息示例:
asyncapi.yml
1 components: 2 messages: 3 UserNotification: 4 name: UserNotification 5 title: User Notification 6 summary: Notification sent to a user 7 contentType: application/json 8 payload: 9 $ref: '#/components/schemas/Notification' 10 examples: 11 - name: EmailNotification 12 summary: Example email notification 13 payload: 14 userId: "123e4567-e89b-12d3-a456-426614174000" 15 type: "email" 16 message: "Welcome to our service!" 17 priority: "medium"
发布操作
发布操作表示您的服务发送到通道的消息:
asyncapi.yml
1 operations: 2 publishOrderStatus: 3 action: send 4 channel: 5 $ref: '#/channels/order~1status' 6 summary: Publish order status update 7 description: Send order status updates to subscribers 8 message: 9 $ref: '#/components/messages/OrderStatus'
订阅操作
订阅操作表示您的服务从通道接收的消息:
asyncapi.yml
1 operations: 2 subscribeToUserSignups: 3 action: receive 4 channel: 5 $ref: '#/channels/user~1signup' 6 summary: Subscribe to user signups 7 description: Receive notifications when users sign up 8 message: 9 $ref: '#/components/messages/UserSignup'
双向通信
您可以为同一个通道定义发布和订阅操作,以启用双向通信:
asyncapi.yml
1 operations: 2 sendChatMessage: 3 action: send 4 channel: 5 $ref: '#/channels/chat~1room' 6 summary: Send chat message 7 description: Send a message to a chat room 8 receiveChatMessage: 9 action: receive 10 channel: 11 $ref: '#/channels/chat~1room' 12 summary: Receive chat message 13 description: Receive messages from a chat room