简体   繁体   中英

How to invoke an aws lambda function from another aws lambda in Java?

I have a code in java that returns an integer value. for example:

public class Hello {

    public int myHandler(Object name, Context context) {

        int count = 5;
        return count;
    }
}

I have uploaded this code on AWS with the handler name as example.Hello::myHandler and function name as AWSLAMBDA under the us-east-2 region.

Now I want to write another code in Java which invokes the output value (count) of the earlier code. Note that count is an integer. Since I am a novice in both java and aws. Kindly help me with this and please provide a simple explanation if possible.

  • This is the code snippet example aws sdk
  • To invoke a function asynchronously, set InvocationType to Event
  • To invoke a function synchronously, set InvocationType to RequestResponse (which is the default value).
  • The calling lambda should have a role with attached policy having lambda:InvokeFunction action.
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.lambda.AWSLambdaClientBuilder;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.model.InvokeResult;

AWSLambda client = AWSLambdaClientBuilder.standard().build();
InvokeRequest request = new InvokeRequest().withFunctionName("MyFunction").withInvocationType("RequestResponse").withLogType("Tail").withClientContext("MyApp")
        .withPayload(ByteBuffer.wrap("fileb://file-path/input.json".getBytes())).withQualifier("1");
InvokeResult response = client.invoke(request);

Besides the Java code you also need to make sure that the policy attached to your Lambda function is actually able to invoke the second Lambda function. Otherwise, the Java snippet will fail since the invoking Lambda misses the permission to invoke other functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM