如何从 Java 代码调用 AWS lambda 函数/处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41616806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:59:58  来源:igfitidea点击:

How to invoke the AWS lambda function / handler from Java code

javaaws-lambdaaws-sdk

提问by prasad kp

I am new to AWS lambda I have created a lambda function with handler

我是 AWS lambda 的新手,我创建了一个带处理程序的 lambda 函数

example.Orders::orderHandler

And this is the custom handler, now I want to invoke this from my Java program how do I need to this.

这是自定义处理程序,现在我想从我的 Java 程序中调用它,我需要这样做。

回答by Jeshan Babooa

The 2 methods in this class should be able to help you. One is for if you need to pass in a payload, the other if the payload is null.

本课程中的 2 个方法应该能够帮助您。一个是如果你需要传入一个有效载荷,另一个是如果有效载荷为空。

However, you need to bear one thing in mind: the function name may not be the same as the handler (the latter here is example.Orders::orderHandler). The handler name is notused when invoking its function.

但是,您需要记住一件事:函数名称可能与处理程序名称不同(这里是后者example.Orders::orderHandler)。调用其函数时使用处理程序名称。

So, if you have a function with the function name'myFunction' that behind the scenes call your example.Orders::orderHandlerhandler, then this is what you would pass into the run methods below.

因此,如果您有一个函数名为“myFunction”的函数,它在后台调用您的example.Orders::orderHandlerhandler,那么这就是您将传递给下面的 run 方法的内容。

import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambdaAsyncClient;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;

class LambdaInvoker {

    public void runWithoutPayload(String region, String functionName) {
        runWithPayload(region, functionName, null);
    }

    public void runWithPayload(String region, String functionName, String payload) {
        AWSLambdaAsyncClient client = new AWSLambdaAsyncClient();
        client.withRegion(Regions.fromName(region));

        InvokeRequest request = new InvokeRequest();
        request.withFunctionName(functionName).withPayload(payload);
        InvokeResult invoke = client.invoke(request);
        System.out.println("Result invoking " + functionName + ": " + invoke);
    }
}

回答by muTheTechie

I followed the following code and just printed the response from the Lambda

我按照下面的代码,只是打印了来自 Lambda 的响应

AWSLambdaAsyncClient lambdaClient = new AWSLambdaAsyncClient();
    lambdaClient.withRegion(Region.getRegion(Regions.US_WEST_2));
    InvokeRequest invokeRequest = new InvokeRequest();
    invokeRequest.setInvocationType("RequestResponse"); // ENUM RequestResponse or Event
    invokeRequest.withFunctionName("FUNCTION NAME").withPayload(payload);
    InvokeResult invoke = lambdaClient.invoke(invokeRequest);
    try {
        // PRINT THE RESPONSE
        String val = new String(invoke.getPayload().array(), "UTF-8");
        System.out.println("Response==> " + val);
    } catch (Exception e) {
        System.out.println("error");
    }

回答by Abhishek Sengupta

Use this LATESTcode to invoke a Lambda Function Synchronously:

使用此最新代码同步调用 Lambda 函数:

    final String AWS_ACCESS_KEY_ID = "xx";
    final String AWS_SECRET_ACCESS_KEY = "xx";

    AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

    // ARN
    String functionName = "XXXX";

    //This will convert object to JSON String
    String inputJSON = new Gson().toJson(userActivity);

    InvokeRequest lmbRequest = new InvokeRequest()
            .withFunctionName(functionName)
            .withPayload(inputJSON);

    lmbRequest.setInvocationType(InvocationType.RequestResponse);

    AWSLambda lambda = AWSLambdaClientBuilder.standard()
            .withRegion(Regions.US_EAST_1)
            .withCredentials(new AWSStaticCredentialsProvider(credentials)).build();

    InvokeResult lmbResult = lambda.invoke(lmbRequest);

    String resultJSON = new String(lmbResult.getPayload().array(), Charset.forName("UTF-8"));

    System.out.println(resultJSON);

Use these dependencies to avoid any errors:

使用这些依赖项可以避免任何错误:

    <dependency>
        <groupId>org.codehaus.janino</groupId>
        <artifactId>janino</artifactId>
        <version>2.6.1</version>
    </dependency>

    //Required by BeanstalkDeploy.groovy at runtime
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-lambda</artifactId>
        <version>1.11.207</version>
    </dependency>

回答by Baked Inhalf

As a sidenote, when creating an AWS Lambda Java project in Eclipse, one must also add

作为旁注,在 Eclipse 中创建 AWS Lambda Java 项目时,还必须添加

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-lambda</artifactId>
    <version>1.11.411</version>
</dependency>

to the pom.xml otherwise these imports will fail:

到 pom.xml 否则这些导入将失败:

import com.amazonaws.services.lambda.AWSLambdaAsyncClient;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;

回答by Mark B

You define the handler when you deploy the Lambda function. Only the AWS Lambda service needs to know what your custom handler is. So the handler has no relevance in the Java code that is invoking the function. Anything invoking the Lambda function only needs to know the Lambda function name, not the handler name.

您在部署 Lambda 函数时定义处理程序。只有 AWS Lambda 服务需要知道您的自定义处理程序是什么。因此处理程序与调用该函数的 Java 代码无关。调用 Lambda 函数的任何内容只需要知道 Lambda 函数名称,而不是处理程序名称。

In Java you would invoke the Lambda function via the AWSLambdaClient.invoke()method documented here.

在 Java 中,您将通过此处AWSLambdaClient.invoke()记录的方法调用 Lambda 函数。