You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将基于NestJS的请求响应式微服务API部署到WSO2 AM?

解决WSO2 API Manager部署NestJS TCP微服务流式API的404问题

1. 修正AsyncAPI YAML适配WSO2要求

由于你将请求响应式API标记为Pub模式,需确保AsyncAPI定义符合WSO2流式API的解析规则:

  • Server配置:将AsyncAPI的servers指向WSO2 AM的WebSocket端点(而非本地TCP地址),本地TCP服务作为后端端点在WSO2中单独配置。示例:
    servers:
      wso2-socketio:
        url: ws://<WSO2_HOST>:9099
        protocol: socketio
    
  • 请求响应映射:利用WSO2扩展x-wso2-operation指定响应通道,模拟请求响应模式(AsyncAPI原生不支持)。示例:
    channels:
      user/request:
        publish:
          operationId: userRequest
          x-wso2-operation:
            responseChannel: user/response
          message:
            payload:
              type: object
              properties:
                id: { type: integer }
                name: { type: string }
      user/response:
        subscribe:
          operationId: userResponse
          message:
            payload:
              type: object
              properties:
                status: { type: string }
                data: { type: object }
    

2. WSO2 AM流式API导入与后端配置

  • 导入AsyncAPI时,选择流式API类型,避免误选REST API。
  • 配置后端端点:在API的Endpoint Configuration中,将NestJS TCP微服务地址(如tcp://localhost:3000)设为WebSocket/Socket.io后端,同时启用WSO2的TCP桥接功能——在deployment.toml中添加:
    [apim.ws]
    enable = true
    tcp_bridge_enable = true
    
  • 部署API到目标环境(Production/Sandbox),确认WSO2网关的WebSocket端口(默认9099)已开放。

3. 正确的订阅与测试流程

  • 获取WebSocket认证令牌:订阅API后,生成带WebSocket权限的访问令牌(需确保订阅的应用包含对应API的权限)。
  • 使用wscat测试的正确命令:
    wscat -c ws://<WSO2_HOST>:9099/<API_CONTEXT>/<API_VERSION> -H "Authorization: Bearer <ACCESS_TOKEN>"
    
    替换<API_CONTEXT>和<API_VERSION>为你部署的API上下文与版本,例如ws://localhost:9099/user-service/v1。
  • 发送消息时,需对应AsyncAPI中定义的channel路径,比如向user/request通道发送请求数据,再从user/response接收响应。

4. 404错误排查要点

  • 查看WSO2网关日志:<WSO2_HOME>/repository/logs/gateway.log会记录路径不匹配、端点连接失败等细节,定位问题根源。
  • 验证NestJS TCP服务可用性:用telnet localhost 3000测试端口是否可访问,确认微服务正常运行。
  • 检查API路由匹配:WSO2会根据AsyncAPI的channel生成WebSocket路由,确保测试时使用的路径与channel名称一致(如/user/request)。

5. NestJS微服务适配调整

确保NestJS能处理WSO2桥接的TCP请求:

  • 控制器中监听对应channel的消息模式:
    @MessagePattern('user/request')
    handleUserRequest(data: any) {
      return { status: 'success', data: { id: data.id, name: `Hello ${data.name}` } };
    }
    
  • 确认TCP微服务配置正确:
    async function bootstrap() {
      const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
        transport: Transport.TCP,
        options: { host: 'localhost', port: 3000 },
      });
      await app.listen();
    }
    bootstrap();
    

内容的提问来源于stack exchange,提问作者Tan Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:22:19