本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
在 API Gateway 中設定 Lambda 代理整合與承載回應串流
當您設定回應承載串流時,您可以在資源的整合請求中指定傳輸模式。您可以在整合請求中設定這些設定,以控制 API Gateway 在整合回應之前和期間的行為。
回應串流的 Lambda 函數範例
您的 Lambda 函數必須遵循 用於回應串流的 Lambda 代理整合格式。我們建議您使用三個範例 Lambda 函數之一來測試回應串流。當您建立 Lambda 函數時,請務必執行下列動作:
-
為您的函數提供足夠的逾時。我們建議您設定至少 1 分鐘的逾時,以了解回應串流。當您建立生產資源時,請確定 Lambda 函數逾時涵蓋完整的請求週期。如需詳細資訊,請參閱設定 Lambda 函數逾時。
-
使用最新的 Node.js 執行時間。
使用可使用 Lambda 回應串流的區域。
- Using HttpResponseStream.from
-
下列程式碼範例使用
awslambda.HttpResponseStream()方法將 JSON 中繼資料物件和承載串流回用戶端,而不使用管道方法。您不需要建立分隔符號。如需詳細資訊,請參閱撰寫啟用回應串流的 Lambda 函數。export const handler = awslambda.streamifyResponse( async (event, responseStream, context) => { const httpResponseMetadata = { "statusCode": 200, "headers": { "x-foo": "bar" }, "multiValueHeaders": { "x-mv1": ["hello", "world"], "Set-Cookie": ["c1=blue", "c2=red"] } }; responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata); await new Promise(r => setTimeout(r, 1000)); // synthetic delay responseStream.write("First payload "); await new Promise(r => setTimeout(r, 1000)); // synthetic delay responseStream.write("Final payload"); responseStream.end(); }); - Using the pipeline method
-
Lambda 建議您在撰寫啟用回應串流的函數時,使用原生 Node.js 執行時間提供的
awslambda.streamifyResponse()裝飾項目,以及pipeline()方法。當您使用管道方法時,您不需要建立分隔符號,Lambda 會為您執行此操作。如需詳細資訊,請參閱撰寫啟用回應串流的 Lambda 函數。下列程式碼範例會將 JSON 中繼資料物件和三個承載串流回用戶端。
import { pipeline } from 'node:stream/promises'; import { Readable } from 'node:stream'; export const handler = awslambda.streamifyResponse( async (event, responseStream, context) => { const httpResponseMetadata = { statusCode: 200, headers: { "Content-Type": "text/plain", "X-Custom-Header": "Example-Custom-Header" } }; responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata); const dataStream = Readable.from(async function* () { yield "FIRST payload\n"; await new Promise(r => setTimeout(r, 1000)); yield "SECOND payload\n"; await new Promise(r => setTimeout(r, 1000)); yield "THIRD payload\n"; await new Promise(r => setTimeout(r, 1000)); }()); await pipeline(dataStream, responseStream); } ); - Without using the pipeline method
-
下列程式碼範例會將 JSON 中繼資料物件和三個承載串流回用戶端,而不使用
awslambda.HttpResponseStream()方法。如果沒有awslambda.HttpResponseStream()方法,您必須在中繼資料和承載之間包含 8 個 null 位元組的分隔符號。export const handler = awslambda.streamifyResponse(async (event, response, ctx) => { response.write('{"statusCode": 200, "headers": {"hdr-x": "val-x"}}'); response.write("\x00".repeat(8)); // DELIMITER await new Promise(r => setTimeout(r, 1000)); response.write("FIRST payload"); await new Promise(r => setTimeout(r, 1000)); response.write("SECOND payload"); await new Promise(r => setTimeout(r, 1000)); response.write("FINAL payload"); response.end(); });
建立 Lambda 代理整合與承載回應串流
下列程序說明如何建立與承載回應串流的 Lambda 代理整合。使用範例 Lambda 函數或建立您自己的函數。
- AWS 管理主控台
-
建立與承載回應串流的 Lambda 代理整合
-
在以下網址登入 API Gateway 主控台:https://console.aws.amazon.com/apigateway
。 選擇 REST API。
選擇建立資源。
針對資源名稱,輸入
streaming。選擇建立資源。
選取 /streaming 資源後,選擇建立方法。
針對方法類型,選擇任何。
對於 整合類型,選擇 Lambda。
選擇 Lambda 代理整合。
針對回應傳輸模式,選擇串流。
針對 Lambda 函數,選擇 Lambda 函數的名稱。
API Gateway 主控台會自動使用 InvokeWithResponseStream API 來叫用 Lambda 函數。您負責撰寫已啟用回應串流功能的 Lambda 函數。如需範例,請參閱 回應串流的 Lambda 函數範例。
選擇建立方法。
建立方法之後,請部署您的 API。
部署 API
選擇部署 API。
針對階段,選取新階段。
針對階段名稱,輸入
prod。在描述,請輸入描述。
選擇部署。
-
- AWS CLI
-
下列程序說明如何匯入新的 API,並將
responseTransferMode設定為STREAM。如果您有現有的整合 API 並想要修改responseTransferMode,請參閱 更新 Lambda 代理整合的回應傳輸模式。使用承載回應串流建立新的 API
-
複製下列 Open API 檔案,然後將其儲存為
ResponseStreamDemoSwagger.yaml。在此檔案中,responseTransferMode設定為STREAM,而整合 URI 設定為arn:aws:apigateway:us-west-1:lambda:path/2021-11-15/functions/arn:aws:lambda:us-west-1:111122223333:function:my-function-name/response-streaming-invocations。將 中的函數名稱取代
my-function為啟用串流的函數,並將登入資料取代為具有允許apigateway服務呼叫 Lambda 函數之政策的 IAM 角色。openapi: "3.0.1" info: title: "ResponseStreamingDemo" version: "2025-04-28T17:28:25Z" servers: - url: "{basePath}" variables: basePath: default: "prod" paths: /lambda: get: x-amazon-apigateway-integration: httpMethod: "POST" uri: "arn:aws:apigateway:us-west-1:lambda:path/2021-11-15/functions/arn:aws:lambda:us-west-1:111122223333:function:my-function-name/response-streaming-invocations" type: "aws_proxy" timeoutInMillis: 90000 responseTransferMode: "STREAM" credentials: "arn:aws:iam::111122223333:role/apigateway-lambda-role"您可以使用 Lambda 的
add-permission命令來新增以資源為基礎的許可,而不是為登入資料提供 IAM 角色。 使用下列
import-rest-api命令匯入您的 OpenAPI 定義:aws apigateway import-rest-api \ --body 'fileb://~/ResponseStreamDemoSwagger.yaml' \ --parameters endpointConfigurationTypes=REGIONAL \ --region us-west-1使用下列
create-deployment命令將您的新 API 部署到階段:aws apigateway create-deployment \ --rest-api-ida1b2c2\ --stage-name prod \ --region us-west-1
-
更新 Lambda 代理整合的回應傳輸模式
下列程序說明如何更新 Lambda 代理整合的回應傳輸模式。當您將回應傳輸模式變更為串流時,請更新您的 Lambda 函數,使其遵守回應串流的要求。使用範例 Lambda 函數或建立您自己的函數。
- AWS 管理主控台
-
更新 Lambda 代理整合的回應傳輸模式
-
在以下網址登入 API Gateway 主控台:https://console.aws.amazon.com/apigateway
。 選擇 REST API。
選擇一個方法。
在整合請求索引標籤上,於整合請求設定下,選擇編輯。
針對回應傳輸模式,選擇串流。
針對 Lambda 函數,選擇 Lambda 函數的名稱。
選擇儲存。
更新方法後,請部署您的 API。
部署 API
選擇部署 API。
針對階段,選取新階段。
針對階段名稱,輸入
prod。在描述,請輸入描述。
選擇部署。
-
- AWS CLI
-
更新您的 Lambda 函數以啟用串流。
使用下列 AWS CLI 命令來更新整合的整合 URI 和回應傳輸模式:
aws apigateway update-integration \ --rest-api-ida1b2c3\ --resource-idaaa111\ --http-method ANY \ --patch-operations "[{\"op\":\"replace\",\"path\":\"/uri\",\"value\":\"arn:aws:apigateway:us-west-1:lambda:path/2021-11-15/functions/arn:aws:lambda:us-west-1:111122223333:function:my-function-name/response-streaming-invocations\"}, {\"op\":\"replace\",\"path\":\"/responseTransferMode\",\"value\":\"STREAM\"}]" \ --region us-west-1-
重新部署 API 以使變更生效。