Jump to content

How to Use Azure Functions with MongoDB Atlas in Java


Recommended Posts

Guest denverbrittain
Posted

Cloud computing is one of the most discussed topics in the tech industry. Having the ability to scale your infrastructure up and down instantly is just one of the many benefits associated with serverless apps. In this article, we are going write the function as a service (FaaS) — i.e., a serverless function that will interact with data via a database, to produce meaningful results. FaaS can also be very useful in A/B testing when you want to quickly release an independent function without going into actual implementation or release. In this article, you'll learn how to use MongoDB Atlas, a cloud database, when you're getting started with Azure functions in Java.

 

 

Prerequisites

 

 

 

 

  1. A Microsoft Azure account that we will be using for running and deploying our serverless function. If you don't have one, you can sign up for free.
  2. A MongoDB Atlas account, which is a cloud-based document database. You can sign up for an account for free.
  3. IntelliJ IDEA Community Edition to aid our development
    activities for this tutorial. If this is not your preferred IDE, then you can use other IDEs like Eclipse, Visual Studio, etc., but the steps will be slightly different.
  4. An Azure supported Java Development Kit (JDK) for Java, version 8 or 11.
  5. A basic understanding of the Java programming language.

 

Serverless function: Hello World!

 

 

 

 

Getting started with the Azure serverless function is very simple, thanks to the Azure IntelliJ plugin, which offers various features — from generating boilerplate code to the deployment of the Azure function. So, before we jump into actual code, let's install the plugin.

 

 

Installing the Azure plugin

 

 

 

 

The Azure plugin can be installed on IntelliJ in a very standard manner using the IntelliJ plugin manager. Open Plugins and then search for "Azure Toolkit for IntelliJ" in the Marketplace. Click Install.

 

 

 

mediumvv2px400.png.b995817a99cf053f22f90b9e8a4bf11e.png

 

 

 

With this, we are ready to create our first Azure function.

 

 

First Azure function

 

 

 

 

Now, let's create a project that will contain our function and have the necessary dependencies to execute it. Go ahead and select File > New > Project from the menu bar, select Azure functions from Generators as shown below, and hit Next.

 

 

 

mediumvv2px400.png.ed5e1cfbd4e861d38ac6fb308aea0581.png

 

 

 

Now we can edit the project details if needed, or you can leave them on default.

 

 

 

mediumvv2px400.png.3e9d696ef117affd32edc77a7fe12f33.png

 

 

 

In the last step, update the name of the project and location.

 

 

 

mediumvv2px400.png.488467f1ae3839be79fe9469f1f4df19.png

 

 

 

With this complete, we have a bootstrapped project with a sample function implementation. Without further ado, let's run this and see it in action.

 

 

 

mediumvv2px400.png.dbbd4476cc4c0deec362382cdda06257.png

 

 

 

Deploying and running

 

 

 

 

We can deploy the Azure function either locally or on the cloud. Let's start by deploying it locally. To deploy and run locally, press the play icon against the function name on line 20, as shown in the above screenshot, and select run from the dialogue.

 

 

 

mediumvv2px400.png.a2407d56c2dbe588e399f72d7d3e8aec.png

 

 

 

Copy the URL shown in the console log and open it in the browser to run the Azure function.

 

 

 

mediumvv2px400.png.a0752ffbebe433c62f70b574d2b5ac6d.png

 

 

 

This will prompt passing the name as a query parameter as defined in the bootstrapped function.

 

 

 

 

 

if (name == null) {

return request.createResponseBuilder(HttpStatus.BAD_REQUEST)

.body("Please pass a name on the query string or in the request body").build();

} else {

return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();

}

 

 

 

 

 

Update the URL by appending the query parameter name to

http://localhost:XXXXX/api/HttpExample?name=World, which will print the desired result.

 

 

 

mediumvv2px400.png.773539f92ae4b94afd5fee677527a702.png

 

 

 

To learn more, you can also follow the official guide.

 

 

Connecting the serverless function with MongoDB Atlas

 

 

 

 

In the previous step, we created our first Azure function, which takes user input and returns a result. But real-world applications are far more complicated than this. In order to create a real-world function, which we will do in the next section, we need to

understand how to connect our function with a database, as logic operates over data and databases hold the data.

 

 

 

Similar to the serverless function, let's use a database that is also on the cloud and has the ability to scale up and down as needed. We'll be using MongoDB Atlas, which is a document-based cloud database.

 

 

Setting up an Atlas account

 

 

 

 

Creating an Atlas account is very straightforward, free forever, and perfect to validate any MVP project idea, but if you need a guide, you can follow the documentation.

 

 

Adding the Azure function IP address in Atlas Network Config

 

 

 

 

The Azure function uses multiple IP addresses instead of a single address, so let's add them to Atlas. To get the range of IP addresses, open your Azure account and search networking inside your Azure virtual machine. Copy the outbound addresses from outbound traffic.

 

One of the steps while creating an account with Atlas is to add the IP address for accepting incoming connection requests. This is essential to prevent unwanted access to our database. In our case, Atlas will get all the connection requests from the Azure function, so let's add this address.

 

 

 

mediumvv2px400.png.2ea13e2ff20ab4eb20663e6a88a4b764.png

 

 

 

Add these to the IP individually under Network Access.

 

 

 

mediumvv2px400.png.9bcf93caf0cba48f081cd803d7dfe083.png

 

 

 

Installing dependency to interact with Atlas

 

 

 

 

There are various ways of interacting with Atlas. Since we are building a service using a serverless function in Java, my preference is to use MongoDB Java driver. So, let's add the dependency for the driver in the build.gradle file.

 

 

 

 

 

dependencies {

implementation 'com.microsoft.azure.functions:azure-functions-java-library:3.0.0'

// dependency for MongoDB Java driver

implementation 'org.mongodb:mongodb-driver-sync:4.9.0'

}

 

 

 

 

 

With this, our project is ready to connect and interact with our cloud database.

 

 

Building an Azure function with Atlas

 

 

 

 

With all the prerequisites done, let's build our first real-world function using the MongoDB sample dataset for movies. In this project, we'll build two functions: One returns the count of the

total movies in the collection, and the other returns the movie document based on the year of release.

 

 

 

Let's generate the boilerplate code for the function by right-clicking on the package name and then selecting New > Azure function class. We'll call this function class Movies.

 

 

 

 

 

public class Movies {

/**

* This function listens at endpoint "/api/Movie". Two ways to invoke it using "curl" command in bash:

* 1. curl -d "HTTP Body" {your host}/api/Movie

* 2. curl {your host}/api/Movie?name=HTTP%20Query

*/

@FunctionName("Movies")

public HttpResponseMessage run(

@HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,

final ExecutionContext context) {

context.getLogger().info("Java HTTP trigger processed a request.");

 

// Parse query parameter

String query = request.getQueryParameters().get("name");

String name = request.getBody().orElse(query);

 

if (name == null) {

return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();

} else {

return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();

}

}

}

 

 

 

 

 

Now, let's:

 

  1. Update @FunctionName parameter from Movies to getMoviesCount.
  2. Rename the function name from run to getMoviesCount.
  3. Remove the query and name variables, as we don't have any query parameters.

 

Our updated code looks like this.

 

 

 

 

 

public class Movies {

 

@FunctionName("getMoviesCount")

public HttpResponseMessage getMoviesCount(

@HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,

final ExecutionContext context) {

context.getLogger().info("Java HTTP trigger processed a request.");

 

return request.createResponseBuilder(HttpStatus.OK).body("Hello").build();

}

}

 

 

 

 

 

To connect with MongoDB Atlas using the Java driver, we first need a connection string that can be found when we press to connect to our cluster on our Atlas account. For details, you can also refer to the documentation.

 

 

 

mediumvv2px400.png.93c2af5ef4c95a2ab42fd574a0bbe1af.png

 

 

 

Using the connection string, we can create an instance of MongoClients that can be used to open connection from the database.

 

 

 

 

 

public class Movies {

 

private static final String MONGODB_CONNECTION_URI = "mongodb+srv://xxxxx@cluster0.xxxx.mongodb.net/?retryWrites=true&w=majority";

private static final String DATABASE_NAME = "sample_mflix";

private static final String COLLECTION_NAME = "movies";

private static MongoDatabase database = null;

 

private static MongoDatabase createDatabaseConnection() {

if (database == null) {

try {

MongoClient client = MongoClients.create(MONGODB_CONNECTION_URI);

database = client.getDatabase(DATABASE_NAME);

} catch (Exception e) {

throw new IllegalStateException("Error in creating MongoDB client");

}

}

return database;

}

 

/*@FunctionName("getMoviesCount")

public HttpResponseMessage run(

@HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,

final ExecutionContext context) {

context.getLogger().info("Java HTTP trigger processed a request.");

 

return request.createResponseBuilder(HttpStatus.OK).body("Hello").build();

}*/

}

 

 

 

 

 

We can query our database for the total number of movies in the collection, as shown below.

 

long totalRecords=database.getCollection(COLLECTION_NAME).countDocuments();

 

Updated code for getMoviesCount function looks like this.

 

 

 

 

 

@FunctionName("getMoviesCount")

public HttpResponseMessage getMoviesCount(

@HttpTrigger(name = "req",

methods = {HttpMethod.GET},

authLevel = AuthorizationLevel.ANONYMOUS

) HttpRequestMessage<Optional<String>> request,

final ExecutionContext context) {

 

if (database != null) {

long totalRecords = database.getCollection(COLLECTION_NAME).countDocuments();

return request.createResponseBuilder(HttpStatus.OK).body("Total Records, " + totalRecords + " - At:" + System.currentTimeMillis()).build();

} else {

return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).build();

}

}

 

 

 

 

 

Now let's deploy this code locally and on the cloud to validate the output. We'll use Postman.

 

 

 

mediumvv2px400.png.265749c678aa3efaba00d01818b9dfd9.png

 

 

 

Copy the URL from the console output and paste it on Postman to validate the output.

 

 

 

mediumvv2px400.png.08c8468579da9ad8c8c7d242dda43cd0.png

 

 

 

Let's deploy this on the Azure cloud on a Linux machine. Click on Azure Explore and select Functions App to create a virtual machine (VM).

 

 

 

mediumvv2px400.png.ce73ac6d79ec9c062c9b78c8e79fdbf8.png

 

 

 

Now right-click on the Azure function and select Create.

 

 

 

mediumvv2px400.png.443ce685de233f9749bc10c5829b8917.png

 

 

 

Change the platform to Linux with Java 1.8.

 

 

 

mediumvv2px400.png.aa21a531c5bcf0ba5efeb7e9f0b5e1c8.png

 

 

 

After a few minutes, you'll notice the VM we just created under Function App. Now, we can deploy our app onto it.

 

 

 

mediumvv2px400.png.5b72e978b53f203763e51ff67e94977d.png

 

 

 

Press Run to deploy it.

 

 

 

mediumvv2px400.png.9bda796338e2bad47a1ae916287b43c1.png

 

 

 

Once deployment is successful, you'll find the URL of the serverless function.

 

 

 

mediumvv2px400.png.a81ae044f7978bf4f678a152f86f4471.png

 

 

 

Again, we'll copy this URL and validate using Postman.

 

 

 

mediumvv2px400.png.83f4b24ab33af7263bf43cb79ecc235f.png

 

 

 

With this, we have successfully connected our first function with

MongoDB Atlas. Now, let's take it to next level. We'll create another function that returns a movie document based on the year of release. Let's add the boilerplate code again.

 

 

 

 

 

@FunctionName("getMoviesByYear")

public HttpResponseMessage getMoviesByYear(

@HttpTrigger(name = "req",

methods = {HttpMethod.GET},

authLevel = AuthorizationLevel.ANONYMOUS

) HttpRequestMessage<Optional<String>> request,

final ExecutionContext context) {

 

}

 

 

 

 

 

To capture the user input year that will be used to query and gather information from the collection, add this code in:

 

 

 

 

 

final int yearRequestParam = valueOf(request.getQueryParameters().get("year"));

 

 

 

 

 

To use this information for querying, we create a Filters object that can pass as input for find function.

 

 

 

 

 

Bson filter = Filters.eq("year", yearRequestParam);

Document result = collection.find(filter).first();

 

The updated code is:

 

@FunctionName("getMoviesByYear")

public HttpResponseMessage getMoviesByYear(

@HttpTrigger(name = "req",

methods = {HttpMethod.GET},

authLevel = AuthorizationLevel.ANONYMOUS

) HttpRequestMessage<Optional<String>> request,

final ExecutionContext context) {

 

final int yearRequestParam = valueOf(request.getQueryParameters().get("year"));

MongoCollection<Document> collection = database.getCollection(COLLECTION_NAME);

 

if (database != null) {

Bson filter = Filters.eq("year", yearRequestParam);

Document result = collection.find(filter).first();

return request.createResponseBuilder(HttpStatus.OK).body(result.toJson()).build();

} else {

return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Year missing").build();

}

}

 

 

 

 

 

Now let's validate this against Postman.

 

 

 

mediumvv2px400.png.56573de1c26e5d929f08c55e79573d3b.png

 

 

 

The last step in making our app production-ready is to secure the connection URI, as it contains credentials and should be kept private. One way of securing it is storing it into an environment variable.

 

 

 

Adding an environment variable in the Azure function can be done via the Azure portal and Azure IntelliJ plugin, as well. For now, we'll use the Azure IntelliJ plugin, so go ahead and open Azure Explore in IntelliJ.

 

 

 

mediumvv2px400.png.2ad698207cfc780ee21080e55ac1e1dc.png

 

 

 

Then, we select Function App and right-click Show Properties.

 

 

 

mediumvv2px400.png.843e29e176f5043b57a26cf714808c2a.png

 

 

 

This will open a tab with all existing properties. We add our property into it.

 

 

 

mediumvv2px400.png.477f24cda090b6814e960969794bc544.png

 

 

 

Now we can update our function code to use this variable. From

 

private static final String MONGODB_CONNECTION_URI = "mongodb+srv://xxxxx:xxxx@cluster0.xxxxx.mongodb.net/?retryWrites=true&w=majority";

 

to

 

private static final String MONGODB_CONNECTION_URI = System.getenv("MongoDB_Connection_URL");

 

After redeploying the code, we are all set to use this app in production.

 

 

Summary

 

 

 

 

Thank you for reading — hopefully you find this article informative! The complete source code of the app can be found on GitHub. If you're looking for something similar using the Node.js runtime, check out the other tutorial on the subject.

 

 

 

With MongoDB Atlas on Microsoft Azure, developers receive access to the most comprehensive, secure, scalable, and cloud–based developer data platform on the market. Now, with the availability of Atlas on the Azure Marketplace, it’s never been easier for users to start building with Atlas while streamlining procurement and billing processes. Get started today through the Atlas on Azure Marketplace listing. If you have any queries or comments, you can share them on the MongoDB forum or tweet @codeWithMohit.

 

Continue reading...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...