在后端服务中使用 @connections 命令 - Amazon API Gateway
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在后端服务中使用 @connections 命令

您的后端服务可以使用以下 WebSocket 连接 HTTP 请求向连接的客户端发送回调消息、获取连接信息或断开客户端连接。

重要

这些请求使用 IAM 授权,因此您必须使用签名版本 4 (SigV4) 对其进行签名。为此,您可以使用 API Gateway 管理 API。有关更多信息,请参阅 ApiGatewayManagementApi

在以下命令中,您需要将 {api-id} 替换为实际的 API ID,该 ID 显示在 API Gateway 控制台中或由 Amazon CLI create-api 命令返回。在使用此命令之前,必须先建立连接。

要向客户端发送回调消息,请使用:

POST https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}

您可以通过使用 Postman 或通过调用 awscurl 来测试此请求,如以下示例所示:

awscurl --service execute-api -X POST -d "hello world" https://{prefix}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}

您需要对命令进行 URL 编码,如以下示例所示:

awscurl --service execute-api -X POST -d "hello world" https://aabbccddee.execute-api.us-east-1.amazonaws.com/prod/%40connections/R0oXAdfD0kwCH6w%3D

要获取客户端的最新连接状态,请使用:

GET https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}

要断开客户端连接,请使用:

DELETE https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}

您可以通过在集成中使用 $context 变量来动态构建回调 URL。例如,如果您将 Lambda 代理集成与 Node.js Lambda 函数一起使用,则可以按如下方式构建 URL 并向连接的客户端发送消息:

import { ApiGatewayManagementApiClient, PostToConnectionCommand, } from "@aws-sdk/client-apigatewaymanagementapi"; export const handler = async (event) => { const domain = event.requestContext.domainName; const stage = event.requestContext.stage; const connectionId = event.requestContext.connectionId; const callbackUrl = `https://${domain}/${stage}`; const client = new ApiGatewayManagementApiClient({ endpoint: callbackUrl }); const requestParams = { ConnectionId: connectionId, Data: "Hello!", }; const command = new PostToConnectionCommand(requestParams); try { await client.send(command); } catch (error) { console.log(error); } return { statusCode: 200, }; };

发送回调消息时,您的 Lambda 函数必须有权调用 API Gateway 管理 API。如果您在连接建立之前或客户端断开连接后发布消息,则可能会收到一条包含 GoneException 的错误。