运行 Lambda 函数 - Amazon 适用于 Ruby 的 SDK
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

运行 Lambda 函数

以下示例在 us-west-2 区域中运行名为 MyGetitemsFunction 的 Lambda 函数。此函数从数据库中返回项目的列表。输入 JSON 如下所示。

{ "SortBy": "name|time", "SortOrder": "ascending|descending", "Number": 50 }

其中:

  • SortBy 是用于对结果进行排序的标准。我们的示例使用 time,这意味着返回的项目将按照它们添加到数据库中的顺序排序。

  • SortOrder 是排序顺序。我们的示例使用 descending,这意味着最新的项目位于列表的最后。

  • Number 是要检索的项目的最大数量 (默认值为 50)。我们的示例使用 10,这意味着获取 10 个最新项目。

输出 JSON 如下所示,其中:

  • STATUS-CODE 是 HTTP 状态代码,200 意味着调用成功。

  • RESULT 是调用的结果,即 successfailure

  • 如果 ERRORresult,则 failure 是错误消息,否则是空字符串

  • 如果 DATAresult,则 success 为返回的结果数组,否则为 nil。

{ "statusCode": "STATUS-CODE", "body": { "result": "RESULT", "error": "ERROR", "data": "DATA" } }

第一步是加载我们使用的模块:

  • aws-sdk 加载我们用于调用 Lambda 函数的适用于 Ruby 的 Amazon SDK 模块。

  • json 加载我们用于封送和解组请求和响应负载的 JSON 模块。

  • os 加载我们用于确保我们可以在 Microsoft Windows 上运行 Ruby 应用程序的操作系统模块。如果您使用的是不同的操作系统,可以删除这些行。

  • 然后,我们创建用于调用 Lambda 函数的 Lambda 客户端。

  • 接下来,我们为请求参数创建哈希并调用 MyGetItemsFunction

  • 最后,我们解析响应,如果成功,我们会输出项目。

# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. require 'aws-sdk-lambda' # v2: require 'aws-sdk' require 'json' # To run on Windows: require 'os' if OS.windows? Aws.use_bundled_cert! end client = Aws::Lambda::Client.new(region: 'us-west-2') # Get the 10 most recent items req_payload = {:SortBy => 'time', :SortOrder => 'descending', :NumberToGet => 10} payload = JSON.generate(req_payload) resp = client.invoke({ function_name: 'MyGetItemsFunction', invocation_type: 'RequestResponse', log_type: 'None', payload: payload }) resp_payload = JSON.parse(resp.payload.string) # , symbolize_names: true) # If the status code is 200, the call succeeded if resp_payload["statusCode"] == 200 # If the result is success, we got our items if resp_payload["body"]["result"] == "success" # Print out items resp_payload["body"]["data"].each do |item| puts item end end end

请参阅 GitHub 上的完整示例