将 Invoke 与 Amazon SDK 或 CLI 配合使用 - Amazon Lambda
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

Invoke 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 Invoke

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 Invoke

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::InvokeRequest request; request.SetFunctionName(LAMBDA_NAME); request.SetLogType(logType); std::shared_ptr<Aws::IOStream> payload = Aws::MakeShared<Aws::StringStream>( "FunctionTest"); *payload << jsonPayload.View().WriteReadable(); request.SetBody(payload); request.SetContentType("application/json"); Aws::Lambda::Model::InvokeOutcome outcome = client.Invoke(request); if (outcome.IsSuccess()) { invokeResult = std::move(outcome.GetResult()); result = true; break; } else { std::cerr << "Error with Lambda::InvokeRequest. " << outcome.GetError().GetMessage() << std::endl; break; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 Invoke

CLI
Amazon CLI

示例 1:同步调用 Lambda 函数

以下 invoke 示例同步调用该 my-function 函数。如果使用 cli-binary-format CLI 版本 2,则 Amazon 选项是必需的。有关更多信息,请参阅《Amazon 命令行界面版本 2 的用户指南》中 Amazon CLI 支持的全局命令行选项

aws lambda invoke \ --function-name my-function \ --cli-binary-format raw-in-base64-out \ --payload '{ "name": "Bob" }' \ response.json

输出:

{ "ExecutedVersion": "$LATEST", "StatusCode": 200 }

有关更多信息,请参阅《Amazon Lambda 开发人员指南》中的同步调用

示例 2:异步调用 Lambda 函数

以下 invoke 示例异步调用该 my-function 函数。如果使用 cli-binary-format CLI 版本 2,则 Amazon 选项是必需的。有关更多信息,请参阅《Amazon 命令行界面版本 2 的用户指南》中 Amazon CLI 支持的全局命令行选项

aws lambda invoke \ --function-name my-function \ --invocation-type Event \ --cli-binary-format raw-in-base64-out \ --payload '{ "name": "Bob" }' \ response.json

输出:

{ "StatusCode": 202 }

有关更多信息,请参阅《Amazon Lambda 开发人员指南》中的异步调用

  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 Invoke

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// FunctionWrapper encapsulates function actions used in the examples. // It contains an AWS Lambda service client that is used to perform user actions. type FunctionWrapper struct { LambdaClient *lambda.Client } // Invoke invokes the Lambda function specified by functionName, passing the parameters // as a JSON payload. When getLog is true, types.LogTypeTail is specified, which tells // Lambda to include the last few log lines in the returned result. func (wrapper FunctionWrapper) Invoke(functionName string, parameters any, getLog bool) *lambda.InvokeOutput { logType := types.LogTypeNone if getLog { logType = types.LogTypeTail } payload, err := json.Marshal(parameters) if err != nil { log.Panicf("Couldn't marshal parameters to JSON. Here's why %v\n", err) } invokeOutput, err := wrapper.LambdaClient.Invoke(context.TODO(), &lambda.InvokeInput{ FunctionName: aws.String(functionName), LogType: logType, Payload: payload, }) if err != nil { log.Panicf("Couldn't invoke function %v. Here's why: %v\n", functionName, err) } return invokeOutput }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 Invoke

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import org.json.JSONObject; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.InvokeRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.lambda.model.InvokeResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; public class LambdaInvoke { /* * Function names appear as * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction * you can retrieve the value by looking at the function in the AWS Console * * Also, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started. * html */ public static void main(String[] args) { final String usage = """ Usage: <functionName>\s Where: functionName - The name of the Lambda function\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String functionName = args[0]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); invokeFunction(awsLambda, functionName); awsLambda.close(); } public static void invokeFunction(LambdaClient awsLambda, String functionName) { InvokeResponse res = null; try { // Need a SdkBytes instance for the payload. JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); SdkBytes payload = SdkBytes.fromUtf8String(json); // Setup an InvokeRequest. InvokeRequest request = InvokeRequest.builder() .functionName(functionName) .payload(payload) .build(); res = awsLambda.invoke(request); String value = res.payload().asUtf8String(); System.out.println(value); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Invoke

JavaScript
适用于 JavaScript 的 SDK(v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

const invoke = async (funcName, payload) => { const client = new LambdaClient({}); const command = new InvokeCommand({ FunctionName: funcName, Payload: JSON.stringify(payload), LogType: LogType.Tail, }); const { Payload, LogResult } = await client.send(command); const result = Buffer.from(Payload).toString(); const logs = Buffer.from(LogResult, "base64").toString(); return { logs, result }; };
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 Invoke

Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun invokeFunction(functionNameVal: String) { val json = """{"inputValue":"1000"}""" val byteArray = json.trimIndent().encodeToByteArray() val request = InvokeRequest { functionName = functionNameVal logType = LogType.Tail payload = byteArray } LambdaClient { region = "us-west-2" }.use { awsLambda -> val res = awsLambda.invoke(request) println("${res.payload?.toString(Charsets.UTF_8)}") println("The log result is ${res.logResult}") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 Invoke

PHP
适用于 PHP 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public function invoke($functionName, $params, $logType = 'None') { return $this->lambdaClient->invoke([ 'FunctionName' => $functionName, 'Payload' => json_encode($params), 'LogType' => $logType, ]); }
  • 有关 API 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 Invoke

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class LambdaWrapper: def __init__(self, lambda_client, iam_resource): self.lambda_client = lambda_client self.iam_resource = iam_resource def invoke_function(self, function_name, function_params, get_log=False): """ Invokes a Lambda function. :param function_name: The name of the function to invoke. :param function_params: The parameters of the function as a dict. This dict is serialized to JSON before it is sent to Lambda. :param get_log: When true, the last 4 KB of the execution log are included in the response. :return: The response from the function invocation. """ try: response = self.lambda_client.invoke( FunctionName=function_name, Payload=json.dumps(function_params), LogType="Tail" if get_log else "None", ) logger.info("Invoked function %s.", function_name) except ClientError: logger.exception("Couldn't invoke function %s.", function_name) raise return response
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 Invoke

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class LambdaWrapper attr_accessor :lambda_client def initialize @lambda_client = Aws::Lambda::Client.new @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Invokes a Lambda function. # @param function_name [String] The name of the function to invoke. # @param payload [nil] Payload containing runtime parameters. # @return [Object] The response from the function invocation. def invoke_function(function_name, payload = nil) params = { function_name: function_name} params[:payload] = payload unless payload.nil? @lambda_client.invoke(params) rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 Invoke

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/** Invoke the lambda function using calculator InvokeArgs. */ pub async fn invoke(&self, args: InvokeArgs) -> Result<InvokeOutput, anyhow::Error> { info!(?args, "Invoking {}", self.lambda_name); let payload = serde_json::to_string(&args)?; debug!(?payload, "Sending payload"); self.lambda_client .invoke() .function_name(self.lambda_name.clone()) .payload(Blob::new(payload)) .send() .await .map_err(anyhow::Error::from) } fn log_invoke_output(invoke: &InvokeOutput, message: &str) { if let Some(payload) = invoke.payload().cloned() { let payload = String::from_utf8(payload.into_inner()); info!(?payload, message); } else { info!("Could not extract payload") } if let Some(logs) = invoke.log_result() { debug!(?logs, "Invoked function logs") } else { debug!("Invoked function had no logs") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的调用

SAP ABAP
SDK for SAP ABAP
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

TRY. DATA(lv_json) = /aws1/cl_rt_util=>string_to_xstring( `{` && `"action": "increment",` && `"number": 10` && `}` ). oo_result = lo_lmd->invoke( " oo_result is returned for testing purposes. " iv_functionname = iv_function_name iv_payload = lv_json ). MESSAGE 'Lambda function invoked.' TYPE 'I'. CATCH /aws1/cx_lmdinvparamvalueex. MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'. CATCH /aws1/cx_lmdinvrequestcontex. MESSAGE 'Unable to parse request body as JSON.' TYPE 'E'. CATCH /aws1/cx_lmdinvalidzipfileex. MESSAGE 'The deployment package could not be unzipped.' TYPE 'E'. CATCH /aws1/cx_lmdrequesttoolargeex. MESSAGE 'Invoke request body JSON input limit was exceeded by the request payload.' TYPE 'E'. CATCH /aws1/cx_lmdresourceconflictex. MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'. CATCH /aws1/cx_lmdresourcenotfoundex. MESSAGE 'The requested resource does not exist.' TYPE 'E'. CATCH /aws1/cx_lmdserviceexception. MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'. CATCH /aws1/cx_lmdtoomanyrequestsex. MESSAGE 'The maximum request throughput was reached.' TYPE 'E'. CATCH /aws1/cx_lmdunsuppedmediatyp00. MESSAGE 'Invoke request body does not have JSON as its content type.' TYPE 'E'. ENDTRY.
  • 有关 API 详细信息,请参阅《Amazon SDK for SAP ABAP API 参考》中的 Invoke

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 Lambda 与 Amazon SDK 配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。