
上QQ阅读APP看书,第一时间看更新
Writing a Lambda function
In this section, we will get down to coding our first Lambda function, as follows:
- In your IDE and build tool of choice (in this literature, we prefer to use IntelliJ and Gradle), create a simple Java project with the package name com.example.
- Add the following dependencies to your dependency management file (or, place them in the classpath). The Gradle code looks as follows (comments are removed for conciseness):
apply plugin: 'java'
apply plugin: 'idea'
repositories {
jcenter()
}
dependencies {
compile group: 'com.amazonaws', name: 'aws-lambda-java-core', version: '1.2.0'
compile group: 'com.amazonaws', name: 'aws-lambda-java-events', version: '2.1.0'
}
- In the package com.example, create a class, Greeter (which will be our LambdaHandler), implementing the RequestHandler interface. Keeping it simple, we will state that the input type is a string and the output type is also a string. Also, let's write a piece of code that takes in the greetee variable, logs it using the LambdaLogger instance, appends it to the predefined string Hello, and returns the result. The first iteration of the code will look as follows:
package com.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class Greeter implements RequestHandler<String,String> {
@Override
public String handleRequest(String greetee, Context context){
LambdaLogger logger = context.getLogger();
logger.log("Lets greet "+ greetee);
return "Hello, " + greetee;
}
}
This very simplistic function is ready to be used. For that, we need to upload it to the AWS environment.