

# 设置后端 Lambda 函数的异步调用
<a name="set-up-lambda-integration-async"></a>

在 Lambda 非代理（自定义）集成中，默认情况下后端 Lambda 函数是同步调用的。这是大多数 REST API 操作的预期行为。但是，某些应用程序通常需要由某个单独的后端组件进行异步执行（如分批操作或长延迟操作）才能运行。在这种情况下，后端 Lambda 函数将进行异步调用，而且前端 REST API 方法不会返回结果。

您可以通过将 `'Event'` 指定为 [Lambda 调用类型](https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html)，为要异步调用的 Lambda 非代理集成配置 Lambda 函数。按如下所示完成此操作：

## 在 API Gateway 控制台中配置 Lambda 异步调用
<a name="asynchronous-invocation-console-examples"></a>

要使所有调用均为异步，请执行以下操作：
+ 在**集成请求**中，添加使用静态值 `'Event'` 的 `X-Amz-Invocation-Type` 标头。

要让客户端决定调用为异步还是同步，请执行以下操作：

1. 在**方法请求**中，添加 `InvocationType` 标头。

1. 在**集成请求**中，添加使用映射表达式 `method.request.header.InvocationType` 的 `X-Amz-Invocation-Type` 标头。

1. 在 API 请求中，对于异步调用，客户端可以包含 `InvocationType: Event` 标头，对于同步调用则可以包含 `InvocationType: RequestResponse`。

## 使用 OpenAPI 配置 Lambda 异步调用
<a name="asynchronous-invocation-OpenAPI-examples"></a>

要使所有调用均为异步，请执行以下操作：
+  将 `X-Amz-Invocation-Type` 标头添加到 **x-amazon-apigateway-integration** 部分。

  ```
  "x-amazon-apigateway-integration" : {
            "type" : "aws",
            "httpMethod" : "POST",
            "uri" : "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-2:123456789012:function:my-function/invocations",
            "responses" : {
              "default" : {
                "statusCode" : "200"
              }
            },
            "requestParameters" : {
              "integration.request.header.X-Amz-Invocation-Type" : "'Event'"
            },
            "passthroughBehavior" : "when_no_match",
            "contentHandling" : "CONVERT_TO_TEXT"
          }
  ```

要让客户端决定调用为异步还是同步，请执行以下操作：

1.  在任何 [OpenAPI 路径项对象](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathItemObject)上添加以下标头。

   ```
   "parameters" : [ {
   "name" : "InvocationType",
   "in" : "header",
   "schema" : {
     "type" : "string"
   }
   } ]
   ```

1.  将 `X-Amz-Invocation-Type` 标头添加到 **x-amazon-apigateway-integration** 部分。

   ```
   "x-amazon-apigateway-integration" : {
             "type" : "aws",
             "httpMethod" : "POST",
             "uri" : "arn:aws:apigateway:us-east-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-2:123456789012:function:my-function/invocations",
             "responses" : {
               "default" : {
                 "statusCode" : "200"
               }
             },
             "requestParameters" : {
               "integration.request.header.X-Amz-Invocation-Type" : "method.request.header.InvocationType"
             },
             "passthroughBehavior" : "when_no_match",
             "contentHandling" : "CONVERT_TO_TEXT"
           }
   ```

1.  在 API 请求中，对于异步调用，客户端可以包含 `InvocationType: Event` 标头，对于同步调用则可以包含 `InvocationType: RequestResponse`。

## 使用 CloudFormation 配置 Lambda 异步调用
<a name="asynchronous-invocation-cfn-examples"></a>

以下 CloudFormation 模板显示如何配置 `AWS::ApiGateway::Method` 来进行异步调用。

要使所有调用均为异步，请执行以下操作：

```
AsyncMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref AsyncResource
      HttpMethod: GET
      ApiKeyRequired: false
      AuthorizationType: NONE
      Integration:
        Type: AWS
        RequestParameters:
          integration.request.header.X-Amz-Invocation-Type: "'Event'"
        IntegrationResponses:
            - StatusCode: '200'
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${myfunction.Arn}$/invocations
      MethodResponses:
        - StatusCode: '200'
```

要让客户端决定调用为异步还是同步，请执行以下操作：

```
AsyncMethodGet:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref Api
      ResourceId: !Ref AsyncResource
      HttpMethod: GET
      ApiKeyRequired: false
      AuthorizationType: NONE
      RequestParameters:
        method.request.header.InvocationType: false
      Integration:
        Type: AWS
        RequestParameters:
          integration.request.header.X-Amz-Invocation-Type: method.request.header.InvocationType
        IntegrationResponses:
            - StatusCode: '200'
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${myfunction.Arn}$/invocations
      MethodResponses:
        - StatusCode: '200'
```

 在 API 请求中，对于异步调用，客户端可以包含 `InvocationType: Event` 标头，对于同步调用则可以包含 `InvocationType: RequestResponse`。