使用软件开发工具包的 Lambda 的代码示例 AWS - AWS SDK 代码示例

文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例

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

使用软件开发工具包的 Lambda 的代码示例 AWS

以下代码示例向您展示了如何 AWS Lambda 使用 AWS 软件开发套件 (SDK)。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景 是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

跨服务示例 是指跨多个 AWS 服务工作的示例应用程序。

更多资源

开始使用

以下代码示例展示了如何开始使用 Lambda。

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

namespace LambdaActions; using Amazon.Lambda; public class HelloLambda { static async Task Main(string[] args) { var lambdaClient = new AmazonLambdaClient(); Console.WriteLine("Hello AWS Lambda"); Console.WriteLine("Let's get started with AWS Lambda by listing your existing Lambda functions:"); var response = await lambdaClient.ListFunctionsAsync(); response.Functions.ForEach(function => { Console.WriteLine($"{function.FunctionName}\t{function.Description}"); }); } }
  • 有关 API 的详细信息,请参阅 AWS SDK for .NET API 参考ListFunctions中的。

C++
SDK for C++
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

C MakeLists .txt cMake 文件的代码。

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS lambda) # Set this project's name. project("hello_lambda") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_lambda.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

hello_lambda.cpp 源文件的代码。

#include <aws/core/Aws.h> #include <aws/lambda/LambdaClient.h> #include <aws/lambda/model/ListFunctionsRequest.h> #include <iostream> /* * A "Hello Lambda" starter application which initializes an AWS Lambda (Lambda) client and lists the Lambda functions. * * main function * * Usage: 'hello_lambda' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient lambdaClient(clientConfig); std::vector<Aws::String> functions; Aws::String marker; // Used for pagination. do { Aws::Lambda::Model::ListFunctionsRequest request; if (!marker.empty()) { request.SetMarker(marker); } Aws::Lambda::Model::ListFunctionsOutcome outcome = lambdaClient.ListFunctions( request); if (outcome.IsSuccess()) { const Aws::Lambda::Model::ListFunctionsResult &listFunctionsResult = outcome.GetResult(); std::cout << listFunctionsResult.GetFunctions().size() << " lambda functions were retrieved." << std::endl; for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: listFunctionsResult.GetFunctions()) { functions.push_back(functionConfiguration.GetFunctionName()); std::cout << functions.size() << " " << functionConfiguration.GetDescription() << std::endl; std::cout << " " << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime( functionConfiguration.GetRuntime()) << ": " << functionConfiguration.GetHandler() << std::endl; } marker = listFunctionsResult.GetNextMarker(); } else { std::cerr << "Error with Lambda::ListFunctions. " << outcome.GetError().GetMessage() << std::endl; result = 1; break; } } while (!marker.empty()); } Aws::ShutdownAPI(options); // Should only be called once. return result; }
  • 有关 API 的详细信息,请参阅 AWS SDK for C++ API 参考ListFunctions中的。

Go
适用于 Go V2 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/lambda" ) // main uses the AWS SDK for Go (v2) to create an AWS Lambda client and list up to 10 // functions in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } lambdaClient := lambda.NewFromConfig(sdkConfig) maxItems := 10 fmt.Printf("Let's list up to %v functions for your account.\n", maxItems) result, err := lambdaClient.ListFunctions(context.TODO(), &lambda.ListFunctionsInput{ MaxItems: aws.Int32(int32(maxItems)), }) if err != nil { fmt.Printf("Couldn't list functions for your account. Here's why: %v\n", err) return } if len(result.Functions) == 0 { fmt.Println("You don't have any functions!") } else { for _, function := range result.Functions { fmt.Printf("\t%v\n", *function.FunctionName) } } }
  • 有关 API 的详细信息,请参阅 AWS SDK for Go API 参考ListFunctions中的。

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

package com.example.lambda; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.LambdaException; import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse; import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListLambdaFunctions { public static void main(String[] args) { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); listFunctions(awsLambda); awsLambda.close(); } public static void listFunctions(LambdaClient awsLambda) { try { ListFunctionsResponse functionResult = awsLambda.listFunctions(); List<FunctionConfiguration> list = functionResult.functions(); for (FunctionConfiguration config : list) { System.out.println("The function name is " + config.functionName()); } } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 AWS SDK for Java 2.x API 参考ListFunctions中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

import { LambdaClient, paginateListFunctions } from "@aws-sdk/client-lambda"; const client = new LambdaClient({}); export const helloLambda = async () => { const paginator = paginateListFunctions({ client }, {}); const functions = []; for await (const page of paginator) { const funcNames = page.Functions.map((f) => f.FunctionName); functions.push(...funcNames); } console.log("Functions:"); console.log(functions.join("\n")); return functions; };
  • 有关 API 的详细信息,请参阅 AWS SDK for JavaScript API 参考ListFunctions中的。

代码示例