House Dzone Refcard 379 Getting Started Serverless
House Dzone Refcard 379 Getting Started Serverless
CONTENTS
Serverless Application
• Building a Sample Serverless
Application
− Build Out the App's Back End
− Add the Serverless Database
Before getting your hands in the soil, it's important to review what BUILDING A SAMPLE SERVERLESS
"serverless" actually means. Of course, servers are still present in APPLICATION
serverless computing; in a serverless architecture, DevOps teams In this tutorial, we'll demonstrate how to build a serverless Java
don't have to worry about building out, configuring, and managing application by creating the leaderboard app shown below:
the hardware. And for developers, serverless means that they can
Figure 1
communicate with the database as if it was a single API endpoint
in a cloud environment. All of which is to say: "Serverless" removes
application architecture maintenance, which creates more room for
innovation.
The intention of this Refcard is to help you easily get started with
serverless application architecture by jumping right into a hands-on
tutorial for building a serverless Java web application.
We'll first build the app's back end using Quarkus to enable CRUD Figure 2
operations on CockroachDB Serverless, which we will then use to store
leaderboard items displayed on the front end. We'll build the front
end using Node.js and React, enabling users to display and add new
leaderboard items. Then, we will deploy the entire solution to Heroku
to make it globally available.
• curl for app testing (you can use another testing tool if
you prefer)
Download the zip file to receive the Java project with a static page,
• Node.js, since we will be using npm to build out React front end
an index.html file (in src/main/resources), one REST API, a
• Git for version control GreetingResource.java file (in src/main/java/org/db), some
• Maven, the build tool unit tests, and some Docker files.
In the Group field, enter "org.db." In the Artifact field, enter @GET
"cockroach-serverless." In the Build Tool field, enter "Maven." Next, @Produces(MediaType.TEXT_PLAIN)
Once the project is configured, select Generate your application. ./mvnw quarkus:dev
Quarkus then displays another window where you can download the
source code (Figure 2). Next, use your browser and navigate to localhost:8080. You will see
index.html being rendered. You can ignore any test output generated
SEE FIGURE 2 IN NEXT COLUMN
in the log.
Append the request to the /hello endpoint to see the static Select Create Cluster, and in the display that pops up, choose
string, Hello RESTEasy. Once this is done, we can add the class
Serverless. The Serverless option requires you to choose your cloud
implementing the actual REST API for our leaderboard app. Create a provider and its region: Set AWS as your provider and use the region
file called LeaderboardItem.java in src/main/java/org/db and closest to your physical location. Optionally, you can modify the
add the following code: cluster name, though we are using the default value, fluffy-possum.
package org.db; Select Create your free cluster to begin the process of creating
import javax.enterprise.inject.Produces; the cluster. In a few seconds, you will see a window containing your
import javax.persistence.Column; connection info:
import javax.persistence.Entity;
Figure 4
import io.quarkus.hibernate.orm.panache.
PanacheEntity;
@Entity
public class LeaderboardItem extends PanacheEntity {
@Column
public String name;
@Column
public double points;
}
The LeaderboardItem class has two fields: name and points. The
class derives from PanacheEntity, so the getters and setters for
name and points fields will be generated automatically. Additionally,
PanacheEntity provides a default identifier, id, which helps to keep
the definition of the LeaderboardItem class clean and simple.
Next, let's implement the actual REST resource for the leaderboard
items. Add the LeaderboardResource.java class in the src/main/
java/org/db directory:
package org.db;
import io.quarkus.hibernate.orm.rest.data.panache.
Be sure to note your database password at this point, as this is the
PanacheEntityResource;
only place where you can reveal it. Otherwise, you'll need to reset the
public interface LeaderboardResource extends password using the CockroachDB dashboard, found in: SQL Users >
PanacheEntityResource Action > Change Password. While you have this window open, you
<LeaderboardItem, Long> {
will also want to grab a few more values that you'll soon need to
}
configure the application.properties class.
Select the Parameters Only dropdown and note the values it presents The item was successfully added to the database. We can check this
(username, host, database, and port): by sending a GET request to http://localhost:8080/leaderboard,
either using curl or a web browser:
Figure 5
Figure 7
First, open your terminal and go to the project's directory. Create a new
directory called webapp in /src/main. Then, create the React project
by entering the following command:
and database with the values taken from CockroachDB Serverless. Use
the cluster name in the JDBC URL:
Figure 6
Let's now customize our web app and add the leaderboard. We will use This component, when given the list of leaderboard items, will render
the PatternFly package to create the table. them as the two-column table we want to display:
Install the PatternFly npm package by invoking the following command Figure 10
from the src/main/webapp directory:
To enable CORS, add the following line to application.properties Next, implement the AddItem.jsx component with the code below:
in the Quarkus project:
import React from 'react';
quarkus.http.cors=true import './AddItem.css'
Now, run the REST API project again by running ./mvnw quarkus:dev class AddItem extends React.Component {
constructor(props) {
and restart the web application by running npm start. Then, open
super(props);
localhost:3000/leaderboard.
this.state = { name: '', points: 0 };
}
You should see something like this:
console.log(this.state);
}
At this point, we can add items using curl or any other REST API client. headers: {
'Content-Type': 'application/json'
Let's see how to do this.
},
ADD ITEMS }).then(function(response) {
We'll now add a form that enables users to add new entries to the return response.json();
});
leaderboard through REST API. The application will also contain two
links that enable the user to switch between the Leaderboard and
event.preventDefault();
Form screens:
}
Figure 12
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.
value}
name="name" onChange={this.
handleChange} placeholder="Name"/>
<br/>
<input type="text" value={this.state.
value}
name="points" onChange={this.
handleChange}placeholder="Points"/>
We start by supplementing the React app with the react router. To do
<br/>
so, install the react-router-dom npm package: <input type="submit" value="Submit" />
</form>
npm install react-router-dom
);
}
Then, in the components directory, add an AddItem.css file:
}
input {
export default AddItem
margin: 5px;
}
The AddItem component consists of a form with two text fields.
The values of these text fields are used to update the state of the Select Add item, then fill in the form:
component. When the user selects the Submit button, a POST request
Figure 13
is sent to our back end.
componentDidMount() {
fetch('http://localhost:8080/leaderboard')
.then(res => res.json())
.then((data) => {
this.setState({ items: data.
sort((a,b)=>{return a.points < b.points}) })
})
.catch(console.log)
}
render () {
You can also use the setInterval JavaScript function to automatically
return (
refresh the leaderboard at the predefined intervals.
<Router>
<div style={{padding: "5px"}}>
DEPLOY TO HEROKU
<Link to="/">Leaderboard</Link><br/>
In this section, we'll deploy our entire solution to Heroku, doing
<Link to="/addItem" >Add item</Link> <br/>
so in a cloud-native way by deploying the back end and front end
</div>
independently. To complete all of the instructions, you will need
<hr/> Heroku and Git accounts, as well as the Heroku CLI installed on your
development machine.
<Routes>
To install Heroku CLI on macOS, use brew:
<Route exact path='/'
element={<Leaderboard items={this.
brew install heroku/brew/heroku
state.items}/>} />
<Route exact path='/addItem'
On Ubuntu, use snap:
element={< AddItem />} />
</Routes> sudo snap install heroku --classic
</Router>
); On other Linux distributions, use a tarball.
}
} On Windows, use one of the dedicated installers.
BACK-END DEPLOYMENT
export default App;
First, let's deploy the back end through Heroku CLI and Git. Start by
Now, run the web app again. You can see the links at the top of the logging into Heroku:
quarkus.http.port=${PORT:8080}
This updates the HTTP port on which our back end is listening for
requests so that it matches the port provided by Heroku. Next, create a
system.properties file:
Figure 17
Before we create our app, we need to collate everything through Git.
Initialize a local Git repository and commit all these files:
git init
git add .
FRONT-END DEPLOYMENT
git commit -am "Initial version"
After ensuring that the back end works, let's deploy the front end.
Now, create the application on Heroku: We will start by updating the code with the Heroku app's URL. In our
case, that is https://afternoon-fortress-35863.herokuapp.
heroku create
com/leaderboard. Your URL will be similar.
Finally, deploy through Git: Update this section of the App.js file — in src/main/webapp/src —
componentDidMount() {
The output of this command should look similar to this: fetch('https://afternoon-fortress-35863.herokuapp.
Figure 15 com/leaderboard')
.then(res => res.json())
.then((data) => {
this.setState({ items: data.sort((a,b)=>{return
a.points < b.points}) })
})
.catch(console.log)
}
event.preventDefault();
}
Now, initialize another repository. Add and commit all of the files,
ensuring to do this from the src/main/webapp subdirectory:
git init
CONCLUSION
git add .
In this Refcard, we walked through the creation and deployment of a
git commit -am "webapp"
Java application, using Quarkus for the back end, React for the front
Create the new Heroku app: end, CockroachDB for our serverless database, Panache for ORM,
and Heroku to deploy the whole package. As you've seen, we quickly
heroku create
connected CockroachDB to our Quarkus back end, but we could have
Finally, deploy the front end through Git: just as easily deployed to Heroku as a Docker container instead. We
also demonstrated how easy it is to automatically generate REST CRUD
git push heroku main
resources using Panache. All of these tools accelerate the development
of serverless apps. And by removing server-centric friction from the
All that remains to do now is to open your application:
application development process, serverless development liberates
heroku open
developers to spend more time on innovation and feature development,
which will ultimately result in better end-user experiences.
You should see the solution up and running:
Figure 18
Copyright © 2022 DZone, Inc. All rights reserved. No part of this publication
may be reproduced, stored in a retrieval system, or transmitted, in any form or
by means of electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.