Serverless FaaS With AWS Lambda and Java
Get your feet with serverless architecture using AWS Lambda, Couchbase, and some Java code. See how you can create, test, and update your functions.
Join the DZone community and get the full member experience.
Join For Freewhat is serverless architecture?
serverless architecture runs custom code in ephemeral containers that are fully managed by a third party. the custom code is typically a small part of a complete application. it is also called a function . another name for serverless architecture is functions-as-a-service (faas). the container is ephemeral because it may only last for one invocation. the container may be reused, but that’s not something you can rely upon. as a developer, you upload the code to a faas platform, then the service handles all the capacity, scaling, patching, and administration of the infrastructure to run your code.
an application built using serverless architecture follows the event-driven approach — for example, a slick within an app.
this is very different from a classical architecture, where the application code is typically deployed in an application server, such as tomcat or wildfly. scaling your application means starting additional instances of the application server or spinning up additional containers with the packaged application server. the load balancer needs to be updated with the new ip addresses, and the os needs to be patched, upgraded, and maintained.
serverless architectures explain the difference between the classical programming model and this new serverless architecture.
the faas platform takes your application and divides it into multiple functions. the service spins up additional compute instances to meet the scalability demands of your application. then, the faas platform provides the execution environment and takes care of starting and tearing down the containers to run your function.
read serverless architectures for more details about these images.
one of the big advantages of faas is that you are only charged for the compute time, i.e. the time your code is running. there is no charge when your code is not running.
here's how functions are different from vms and containers:
note that linux containers, instead of docker containers, are used the an implementation for aws lambda.
how is faas different from paas?
as quoted from serverless architectures , a quick answer is provided by the following tweet:
followadrian cockcroft @adrianco
if your paas can efficiently start instances in 20ms that run for half a second, then call it serverless. https://twitter.com/doctor_julz/status/736424613475819520 …
in other words, most paas applications are not geared toward bringing entire applications up and down for every request, whereas faas platforms do exactly this.
abstracting the back-end with faas explain the difference with different *aas offerings. the image from the blog is captured below:
serverless architectures also provide great details about what faas is and is not.
aws lambda , google cloud functions, and azure functions are some of the options for running serverless applications.
this blog will show how to write your first aws lambda function.
what is aws lambda?
aws lambda is a faas service from amazon web services. it runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring, and logging.
aws lambda charges you for the duration your code runs in increments of 100ms. there is no cost associated with storing the lambda function in aws. the first million requests per month are free, and the pricing after that is nominal. read more details on lambda pricing here . it also provides visibility into performance by providing real-time metrics and logs to aws cloudwatch . all you need to do is write the code!
here is a quick introduction:
also check out what’s new in aws lambda from aws reinvent 2016 :
also check out serverless architectural patterns and best practices from aws reinvent 2016:
the code you run on aws lambda is called a lambda function. you upload your code as a zip file or design it using the aws lambda management console . there is built-in support for the aws sdk, which simplifies the ability to call other aws services.
in short, lambda is scalable, serverless computing in the cloud.
aws lambda provides several execution environments:
- node.js – v0.10.36, v4.3.2 (recommended)
- java – java 8
- python – python 2.7
- .net core – .net core 1.0.1 (c#)
this blog will show:
- build a java application that stores a json document to couchbase
- use maven to create a deployment package for java application
- create a lambda function
- update the lambda function
the complete code in this blog is available at github.com/arun-gupta/serverless/tree/master/aws/hellocouchbase .
java application for aws lambda
first, let's look at a java application that will be used for this lambda function. the article programming model for lambda functions in java provides more details about how to write your lambda function code in java.
our lambda function will implemented the pre-defined interface
com.amazonaws.services.lambda.runtime.requesthandler
. the code looks like:
public class hellocouchbase implements requesthandler<request, string> {
couchbasecluster cluster;
bucket bucket;
lambdalogger logger;
@override
public string handlerequest(request request, context context) {
simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss.sss");
string timestamp = dateformat.format(calendar.getinstance().gettime());
logger = context.getlogger();
logger.log("request received: %s" + timestamp);
buttondocument buttondocument = new buttondocument();
buttondocument.setid(context.getawsrequestid());
buttondocument.setrequestid(context.getawsrequestid());
buttondocument.settimestamp(string.valueof(timestamp));
getbucket().upsert(buttondocument.tojson());
return buttondocument.tostring();
}
the
handlerequest
method is where the function code is implemented.
context
provides useful information about the lambda execution environment. some of the information from the context is stored a json document. finally, a
couchbase java sdk
api
upsert
is used to write a json document to the identified couchbase instance.
couchbase on amazon ec2
provides complete instructions to install couchbase on aws ec2.
information about the couchbase server is obtained with:
public couchbasecluster getcluster() {
if (null == cluster) {
logger.log("env: " + system.getenv("couchbase_host"));
cluster = couchbasecluster.create(system.getenv("couchbase_host"));
}
return cluster;
}
this is once again using the couchbase java api
couchbasecluster
as a main entry point to the couchbase cluster. the
couchbase_host
environment variable is passed when the lambda function is created. in our case, this would point to a single node couchbase cluster running on aws ec2.
environment variables were recently introduced
in aws lambda.
finally, you need to access the bucket in the server:
public bucket getbucket() {
while (null == bucket) {
logger.log("trying to connect to the database");
bucket = getcluster().openbucket("serverless", 2l, timeunit.minutes);
try {
thread.sleep(3000);
} catch (exception e) {
logger.log("thread sleep exception: " + e.tostring());
throw new runtimeexception(e);
}
}
return bucket;
}
the bucket name is
serverless
and all json documents are stored in this.
a simple hello world application may be used for creating this function as well.
create an aws lambda deployment package
aws lambda function needs a deployment package. this package is either a
.zip
or
.jar
file that contains all the dependencies of the function. our application is packaged using maven, and so we’ll use a maven plugin to create a deployment package.
the application has a
pom.xml
file with the following plugin fragment:
<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>maven-shade-plugin</artifactid>
<version>2.3</version>
<configuration>
<createdependencyreducedpom>false</createdependencyreducedpom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
more details about maven configuration are available in
creating a .jar deployment package using maven without any ide
. the
maven-shade-plugin
allows us to create an uber-jar including all the dependencies. the
shade
goal is tied to the
package
phase. so the
mvn package
command will generate a single deployment jar.
package the application using the
mvn package
command. this will show the output:
[info] --- maven-jar-plugin:2.4:jar (default-jar) @ hellocouchbase ---
[info] building jar: /users/arungupta/workspaces/serverless/aws/hellocouchbase/hellocouchbase/target/hellocouchbase-1.0-snapshot.jar
[info]
[info] --- maven-shade-plugin:2.3:shade (default) @ hellocouchbase ---
[info] including com.amazonaws:aws-lambda-java-core:jar:1.1.0 in the shaded jar.
[info] including com.couchbase.client:java-client:jar:2.3.6 in the shaded jar.
[info] including com.couchbase.client:core-io:jar:1.3.6 in the shaded jar.
[info] including io.reactivex:rxjava:jar:1.1.8 in the shaded jar.
[info] replacing original artifact with shaded artifact.
[info] replacing /users/arungupta/workspaces/serverless/aws/hellocouchbase/hellocouchbase/target/hellocouchbase-1.0-snapshot.jar with /users/arungupta/workspaces/serverless/aws/hellocouchbase/hellocouchbase/target/hellocouchbase-1.0-snapshot-shaded.jar
[info] ------------------------------------------------------------------------
[info] build success
[info] ------------------------------------------------------------------------
the
target/hello-couchbase-1.0-snapshot.jar
is the shaded jar that will be deployed to aws lambda.
more details about creating a deployment package are at creating a deployment package .
create aws lambda function
create an aws lambda function using aws cli . the cli command, in this case, looks like:
aws lambda create-function \
--function-name helloworld \
--role arn:aws:iam::<account-id>:role/service-role/mylambdarole \
--zip-file fileb:///users/arungupta/workspaces/serverless/aws/hellocouchbase/hellocouchbase/target/hellocouchbase-1.0-snapshot.jar \
--handler org.sample.serverless.aws.couchbase.hellocouchbaselambda \
--description "hello couchbase lambda" \
--runtime java8 \
--region us-west-2 \
--timeout 30 \
--memory-size 1024 \
--publish
in this cli:
-
create-function
creates a lambda function. -
--function-name
provides the function name. the function name is case sensitive. -
--role
specifies amazon resource name (arn) of an iam role that lambda assumes when it executes your function to access any other aws resources. if you’ve executed a lambda function using aws console, then this role is created for you. -
--zip-file
points to the deployment package that was created in the previous step.fileb
is an aws cli specific protocol to indicate that the content uploaded is binary. -
--handler
is the java class that is called to begin execution of the function -
--publish
requests aws lambda to create the lambda function and publish a version as an atomic operation. otherwise, multiple versions may be created and may be published at a later point.
the lambda console shows:
test the aws lambda function
test the aws lambda function using aws cli.
aws lambda invoke \
--function-name hellocouchbaselambda \
--region us-west-2 \
--payload '' \
hellocouchbase.out
it shows the output as:
{
"statuscode": 200
}
the output from the command is stored in
hellocouchbase.out
and looks like:
"{\"id\":\"e6bbe71a-ca4f-11e6-95a7-95f2ed410493\",\"installationid\":null,\"requestid\":\"e6bbe71a-ca4f-11e6-95a7-95f2ed410493\",\"identityid\":null,\"timestamp\":\"2016-12-25 03:12:01.157\"}"
invoking this function stores a json document in couchbase. documents stored in couchbase can be seen using the
couchbase web console
. the login is
administrator
and the password is the ec2 instance id.
all data buckets in this couchbase instance are shown below:
note that the
serverless
bucket is manually created.
clicking on documents shows details of different documents stored in the bucket:
clicking on each document shows more details about the json document:
lambda functions can also be tested using the console:
update an aws lambda function
if the application logic changes then a new deployment package needs to be uploaded for the lambda function. in this case,
mvn package
will create a deployment package and
aws lambda
cli command is used to update the function code:
aws lambda update-function-code \
--function-name hellocouchbaselambda \
--zip-file fileb:///users/arungupta/workspaces/serverless/aws/hellocouchbase/hellocouchbase/target/hellocouchbase-1.0-snapshot.jar \
--region us-west-2 \
--publish
shows the result:
{
"codesha256": "w510ejw/oovsqt2jilg2bpzpaafvqcrryyylqwctcqe=",
"functionname": "hellocouchbaselambda",
"codesize": 6978108,
"memorysize": 1024,
"functionarn": "arn:aws:lambda:us-west-2:<account-id>:function:hellocouchbaselambda:8",
"environment": {
"variables": {
"couchbase_host": "ec2-35-165-249-235.us-west-2.compute.amazonaws.com"
}
},
"version": "8",
"role": "arn:aws:iam::<account-id>:role/service-role/mylambdarole",
"timeout": 30,
"lastmodified": "2016-12-25t04:17:38.717+0000",
"handler": "org.sample.serverless.aws.couchbase.hellocouchbaselambda",
"runtime": "java8",
"description": "java hello couchbase"
}
the function can then be invoked again.
during the writing of this blog post, this was often used to debug the function as well. this is because lambda functions do not have any state or box associated with them. and so you cannot log into a box to check out if the function did not deploy correctly. you can certainly use cloudwatch log statements once the function is working.
Published at DZone with permission of Arun Gupta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments