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

前端 未结 5 1553
耶瑟儿~
耶瑟儿~ 2021-01-19 18:40

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

example.Orders::orderHandler

And this is the custom handler, now I wa

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 19:00

    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.

    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 not used when invoking its function.

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

    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);
        }
    }
    

提交回复
热议问题