将多个方法映射到单个 lambda 函数是完全有效的,现在许多人都在使用这种方法,而不是为每个离散方法创建 api 网关资源和 lambda 函数。
您可能会考虑将所有请求代理到单个函数。查看以下有关创建 API Gateway => Lambda 代理集成的文档:http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-set-up-lambda-proxy-integration-on-proxy-resource
他们的例子在这里很好。类似如下的请求:
POST /testStage/hello/world?name=me HTTP/1.1
Host: gy415nuibc.execute-api.us-east-1.amazonaws.com
Content-Type: application/json
headerName: headerValue
{
"a": 1
}
最终会将以下事件数据发送到您的 AWS Lambda 函数:
{
"message": "Hello me!",
"input": {
"resource": "/{proxy+}",
"path": "/hello/world",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"cache-control": "no-cache",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"headerName": "headerValue",
"Host": "gy415nuibc.execute-api.us-east-1.amazonaws.com",
"Postman-Token": "9f583ef0-ed83-4a38-aef3-eb9ce3f7a57f",
"User-Agent": "PostmanRuntime/2.4.5",
"Via": "1.1 d98420743a69852491bbdea73f7680bd.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "pn-PWIJc6thYnZm5P0NMgOUglL1DYtl0gdeJky8tqsg8iS_sgsKD1A==",
"X-Forwarded-For": "54.240.196.186, 54.182.214.83",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"queryStringParameters": {
"name": "me"
},
"pathParameters": {
"proxy": "hello/world"
},
"stageVariables": {
"stageVariableName": "stageVariableValue"
},
"requestContext": {
"accountId": "12345678912",
"resourceId": "roq9wj",
"stage": "testStage",
"requestId": "deef4878-7910-11e6-8f14-25afc3e9ae33",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": null,
"sourceIp": "192.168.196.186",
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": "PostmanRuntime/2.4.5",
"user": null
},
"resourcePath": "/{proxy+}",
"httpMethod": "POST",
"apiId": "gy415nuibc"
},
"body": "{\r\n\t\"a\": 1\r\n}",
"isBase64Encoded": false
}
}
现在,您可以访问所有标头、url 参数、正文等,并且可以使用它们在单个 Lambda 函数中以不同方式处理请求(基本上实现您自己的路由)。
作为一种意见,我看到了这种方法的一些优点和缺点。其中许多取决于您的具体用例:
-
部署:如果每个 lambda 函数都是离散的,那么您可以独立部署它们,这可能会降低代码更改的风险(微服务策略)。相反,您可能会发现需要单独部署功能会增加复杂性并且很麻烦。
-
自我描述:API Gateway 的界面使您可以极其直观地查看 RESTful 端点的布局 - 名词和动词一目了然。实现您自己的路由可能会以牺牲这种可见性为代价。
-
Lambda 大小和限制:如果您代理全部,那么您最终需要选择一个实例大小、超时等来容纳您的所有 RESTful 端点。如果您创建离散函数,那么您可以更仔细地选择最能满足特定调用需求的内存占用、超时、死信行为等。