Sådan oprettes en serverløs applikation ved hjælp af AWS SAM
I min tidligere artikel talte jeg om, hvordan AWS Chalice hjælper dig med hurtigt at opbygge en Python-baseret serverløs applikation og distribuere den på AWS inden for få minutter.
Mens det var en hurtig og sjov prototype, er Python muligvis ikke det valgte sprog for mange, når det kommer til at køre store produktionsapplikationer.
Mange organisationer bruger Java som deres primære udviklingssprog, og mange udviklere bevæger sig også mod nyere sprog som Go.
I denne artikel vil jeg gennemgå de nødvendige trin til at opbygge og implementere den samme serverløse applikation, der får de seneste nyheder fra Google Nyheder. Men denne gang bruger vi AWS Serverless Application Model (SAM) og Java til vores udvikling.
Ligesom kalken tilbyder AWS SAM CLI et rigt sæt værktøjer, der gør det muligt for udviklere at oprette serverløse applikationer hurtigt.
Forudsætninger
Denne tutorial kræver en AWS-konto. Hvis du ikke allerede har en, skal du fortsætte med at oprette en. Vores applikation vil kun bruge de gratis niveaueressourcer, så omkostninger bør ikke være et problem.
Du skal også konfigurere sikkerhed og oprette brugere og roller for din adgang.
Sådan konfigureres AWS-legitimationsoplysninger
SAM bruger AWS Command Line Interface (CLI) bag kulisserne til at implementere projektet. Hvis du ikke tidligere har brugt AWS's CLI til at arbejde med AWS-ressourcer, kan du installere det ved at følge retningslinjerne her.
Når du er installeret, skal du konfigurere din AWS CLI til at bruge legitimationsoplysningerne fra din AWS-konto.

Sådan installeres SAM
Dernæst skal du installere SAM. Vi bruger Java i denne vejledning, men du kan bruge enhver sprogkørsel understøttet af AWS Lambda.
Bekræft Java-installation
$ java --version openjdk 11.0.8 2020-07-14 OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.8+10) OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.8+10, mixed mode)
Installer SAM CLI
Afhængigt af dit operativsystem, vil installationsvejledningen til SAM CLI variere. Denne artikel dækker instruktionerne til installation af den på MacOS.
Den anbefalede tilgang til installation af SAM CLI på macOS er at bruge Homebrew pakkehåndtering.
Kontroller, at du har Homebrew installeret på denne måde:
$ brew --version Homebrew/homebrew-core (git revision fe68a; last commit 2020-10-15) Homebrew/homebrew-cask (git revision 4a2c25; last commit 2020-10-15)
Hvis ikke, kan du installere Homebrew ved hjælp af følgende kommando:
$ /bin/bash -c "$(curl -fsSL //raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Dernæst skal du installere SAM ved hjælp af følgende kommando:
brew tap aws/tap brew install aws-sam-cli
Bekræft installation af SAM
$ sam --version SAM CLI, version 1.6.2
Sådan oprettes et projekt
Kør derefter sam-init
kommandoen for at oprette et nyt projekt.
sam init -r java11 -d maven --app-template hello-world -n daily-news-java
SAM opretter som standard et Python-projekt. Da vi vil oprette et Java-projekt, skal vi videregive nogle yderligere parametre.
Parametre:
-r java11
: brug Java 11 runtime-d maven
: brug maven som afhængighedsmanager--app-template hello-world
: brug HelloWorld hurtigstartsskabelonen-n daily-news-java
: navnet på vores projekt
Dette opretter en daily-news-java
mappe i dit nuværende bibliotek. Du kan se, at SAM har oprettet flere filer i denne mappe.

Lad os se på App.java
filen.
Den sam-init
kommando skabt en enkel Lambda-funktion, der returnerer JSON krop {"message": "hello world"}
og maskinens IP-adresse, når kaldes. Vi kan nu ændre denne skabelon og tilføje mere kode for at læse nyheder fra Google.
Lad os nu se på template.yml
filen.
Dette indeholder CloudFormation-skabelonen, der opretter vores Amazon API Gateway og AWS Lambda-ressourcer.
Lambda-konfigurationen angiver, at vi har en HelloWorldFunction
lambda, der kører på Java 11
og 512 MB
hukommelse.
API-gateway-konfigurationen definerer en enkelt GET
metode med en /hello
sti, som vi vil bruge til at påkalde API.
Vi bruger Java's interne HTTP- og XML-parseringsbiblioteker, så vi behøver ikke tilføje nogen afhængigheder til vores pom.xml
fil.
Bemærk, at den standard, der pom.xml
leveres som en del af kogepladekoden, kommer med kompilerkilde indstillet til. 1.8.
Vi bliver nødt til at opdatere det til, 11
så vi kan bruge det nye HTTP-bibliotek, der er en del af Java 11.
Da Java er objektorienteret, lad os også oprette en NewsItem
klasse, der indeholder titlen og udgivelsesdatoen for et nyhedsemne.
Bemærk, at vi har tilsidesat toString
metoden. Dette skaber en JSON-repræsentation af objektet og undgår at bruge eventuelle JSON-parseringsbiblioteker.
Next, you need to add a method to fetch the RSS feed from Google, parse it to extract the news title and publication date, and create a list of news items. To do this, add the following code to your App.java
:
Now let’s update the handleRequest
method in App.java
to invoke this method and return the list of news items as result.
Don’t forget to update the unit tests as well. They were written to test the presence of “hello world” in the response and will start failing after our change.
How to Start the Build
From the daily-news-java
folder, run the sam build
command.

This compiles your source code and builds any dependencies that you have in the application. It then moves all the files into the .aws-sam/build
folder so that they are ready to be packaged and deployed. It also updates the template.yml
file accordingly.
How to Test Your Application Locally
Now here’s the beautiful part about SAM. You can deploy and test your application locally! This is really helpful during the development stage when you want to test your code without having to deploy it to AWS.
The SAM CLI provides the sam local
command to run your application locally. This internally uses Docker to simulate the execution environment of Lambda. If you don’t have Docker installed, you can get it from here.
We can locally test our application in two ways:
- Hosting the API locally
- Directly invoking the Lambda function
Let’s take a look at both of these options.
Local Hosting
Use the following command to start the API locally:
sam local start-api
This internally creates a local server and exposes a local endpoint that replicates your REST API.

Once the Docker container is loaded, you can access the API on localhost
, like this:
curl //127.0.0.1:3000/hello
Direct Invocation
Use the following command to invoke the Lambda function:
sam local invoke "HelloWorldFunction" -e events/event.json

This directly invokes the Lambda function (just like we would call the main
method) and passes the event.json
file as payload.
How to Deploy the Project
Let’s deploy the application. From the daily-news-java
folder, run the sam deploy --guided
command. Follow the prompts and provide the required inputs (or just press Enter to accept the defaults).

This deploys our application on AWS using Amazon API Gateway and AWS Lambda. It takes the deployment artifacts that we built with the sam build
command, packages and uploads them to an Amazon S3 bucket created by the AWS SAM CLI, and deploys the application using AWS CloudFormation.



We can now try accessing the API using the endpoint URL provided above.

How to Clean Up Resources
We can use the aws cloudformation delete-stack
commandto delete the AWS CloudFormation stack along with all the resources it created when we ran the sam deploy
command.

Conclusion
Congratulations! You just deployed a serverless application on AWS using AWS SAM. It did involve a bit more work than earlier, but it wasn’t too hard either.
You can now go ahead and make any modifications to your App.java
file and rerun sam deploy
to redeploy your changes.
Den fulde kildekode til denne vejledning kan findes her.
Tak fordi du har været hos mig indtil videre. Håber du kunne lide artiklen. Du kan få kontakt med mig på LinkedIn, hvor jeg regelmæssigt diskuterer teknologi og liv. Se også nogle af mine andre artikler om Medium.
God læselyst ?