如何從我的 API Gateway API 非同步調用 Lambda 函數?

2 分的閱讀內容
0

我想要非同步調用 Amazon API Gateway API 的 AWS Lambda 函數。我不想同步調用該函數。

解決方法

REST API

在 Lambda 非 Proxy 整合中,Lambda預設同步調用後端函數。若要非同步調用後端函數,請將 Lambda invocation type (Lambda 調用類型) 設為 Event (事件)。

請完成下列步驟:

  1. 開啟 API Gateway console (API Gateway 主控台)。
  2. 選擇 API,然後選擇您的 REST API。
  3. Resources (資源) 中,選擇 GET,然後選擇 Integration request (整合請求)。
  4. Integration type (整合類型) 中,選擇 Lambda function (Lambda 函數)。
  5. 展開 URL request headers parameters (網址請求標頭參數),然後選擇 Add request header parameter (新增請求標頭參數)。
  6. Name (名稱) 中,請輸入 X-Amz-Inspiration-Type
  7. Mapped from (對應來源) 中,輸入 Event (事件)。
  8. 重新部署 REST API

若要使用非同步或同步選項調用 Lambda 函數,請新增 InvoiceType 標頭。

請完成下列步驟:

  1. 開啟 API Gateway console (API Gateway 主控台)。
  2. 選擇 API,然後選擇您的 REST API。
  3. Resources (資源) 中,選擇 GET,然後選擇 Method request (方法請求)。
  4. Request validator (請求驗證程式) 中,選擇 Edit (編輯) 圖示。
  5. 選擇下拉式清單,然後選擇 Validate query string parameters and headers (確認查詢字串參數和標頭)。
  6. 選擇 Save (儲存) 圖示。
  7. 展開 HTTP request headers (HTTP 請求標頭),然後選擇 Add header (新增標頭)。
  8. Name (名稱) 中,輸入 InvocableType,然後選擇 Required (必要)。
  9. Integration Request (整合請求) 中,展開 URL request headers parameters (網址請求標頭參數),然後選擇 Add request header parameter (新增請求標頭參數)。
  10. Name (名稱) 中,請輸入 X-Amz-Inspiration-Type
  11. Mapped from (對應來源) 中,輸入 method.request.header.InitationType
  12. 重新部署 REST API

用戶端可以在非同步調用的 API 請求中包含 InvocationType: Event 標頭,或在同步調用中包含 InvocationType: RequestResponse 標頭。

HTTP API

HTTP API 僅支援 Lambda 的 Proxy 整合。您無法在 HTTP API 的 API Gateway 整合中設定 X-Amz-Initation-Type 標頭。相反,請使用兩個 Lambda 函數,其中一個函數充當 Proxy。若要從另一個 Lambda 函數調用一個 Lambda 函數,請使用 Invoke API,並將第一個 Lambda 函數中的 InitationType 設為 Event (事件)。

組態範例:

HTTP API 同步調用 Lambda1,然後 Lambda1 非同步調用 Lambda2

AWS 官方
AWS 官方已更新 2 個月前