服务器

定义服务器 URL 和协议以帮助用户连接到您的事件驱动 API。

以 Markdown 格式查看

AsyncAPI 允许您在 servers 键下指定一个或多个服务器配置。

asyncapi.yml
1servers:
2 production:
3 host: api.yourcompany.com
4 protocol: wss
5 description: Production WebSocket server
6 staging:
7 host: staging.api.yourcompany.com
8 protocol: wss
9 description: Staging WebSocket server

指定服务器对 SDK 和文档都很有价值:

  • 对于 SDK,您的用户在客户端实例化时无需手动指定服务器 URL
  • 对于文档,您的 API 游乐场将自动连接到正确的服务器

协议支持

AsyncAPI 支持各种用于事件驱动通信的协议:

asyncapi.yml
1servers:
2 websocket-server:
3 host: ws.api.yourcompany.com
4 protocol: ws
5 description: WebSocket server for real-time communication
6 mqtt-server:
7 host: mqtt.yourcompany.com
8 protocol: mqtt
9 description: MQTT broker for IoT devices
10 kafka-server:
11 host: kafka.yourcompany.com
12 protocol: kafka
13 description: Kafka cluster for event streaming

命名您的服务器

我们建议为您的服务器提供描述性名称,以明确每个服务器的用途:

asyncapi.yml
1servers:
2 production:
3 host: api.yourcompany.com
4 protocol: wss
5 description: Production WebSocket server
6 staging:
7 host: staging.api.yourcompany.com
8 protocol: wss
9 description: Staging environment for testing
10 development:
11 host: localhost:8080
12 protocol: ws
13 description: Local development server

服务器变量

您可以在服务器配置中使用变量来使其更加灵活:

asyncapi.yml
1servers:
2 production:
3 host: '{environment}.api.yourcompany.com'
4 protocol: wss
5 variables:
6 environment:
7 default: prod
8 enum:
9 - prod
10 - staging
11 description: Environment name

不同通道使用多种协议

如果您有使用不同协议的不同通道,您可以在服务器配置中指定这一点:

asyncapi.yml
1servers:
2 websocket-server:
3 host: ws.api.yourcompany.com
4 protocol: wss
5 description: WebSocket server for real-time notifications
6 mqtt-server:
7 host: mqtt.api.yourcompany.com
8 protocol: mqtt
9 description: MQTT broker for IoT device communication
10 kafka-server:
11 host: kafka.api.yourcompany.com
12 protocol: kafka
13 description: Kafka for high-throughput event streaming
14
15channels:
16 user/notifications:
17 servers:
18 - websocket-server
19 address: user/notifications
20 description: Real-time user notifications via WebSocket
21 device/telemetry:
22 servers:
23 - mqtt-server
24 address: device/telemetry
25 description: IoT device telemetry via MQTT

这允许不同的通道使用最适合其用例的协议。