Micronaut in the Cloud: Intro to MongoDB in Microservices
Micronaut is an open-source, JVM-based framework for building full-stack, modular, easily testable microservice and serverless applications.
Unlike reflection-based IoC frameworks that load and cache reflection data for every single field, method, and constructor in your code, with Micronaut, your application startup time and memory consumption are not bound to the size of your codebase. Micronaut's cloud support is built right in, including support for common discovery services, distributed tracing tools, and cloud runtimes.
This Micronaut tutorial in the cloud we'll deploy an application with MongoDB database.
The first step is to create the application itself, and Micronaut has proper documentation. You have the start code link where you can define the dependencies that you need to write your application. At this point, we need MongoDB-sync dependency.
If you want to run a MongoDB locally, a good option might be a Docker, that you can run with the command below:
docker run -d --name mongodb-instance -p 27017:27017 mongo
The first step is to set up the database configuration. We need to configure the application to run locally and enable it to be overwritten to the production environment.
xxxxxxxxxx
micronaut
application
name mongodb
mongodb.uri $ MONGO_URL `mongodb //localhost 27017/database`
The infrastructure code is ready; the next step is to create the application itself. In this sample, we'll create a small rest-application to store people. Therefore, we'll create a Person
entity.
x
import io.micronaut.core.annotation.Introspected;
import javax.validation.constraints.NotBlank;
public class Person {
private String name;
private String city;
private String country;
//getter and setter
}
The last step is to create a resource where the client can do the request and then the CRUD.
x
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Delete;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import org.bson.conversions.Bson;
import javax.validation.Valid;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
"/people") (
public class PersonController {
private final MongoClient mongoClient;
public PersonController(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
"/{name}") (
public Person show(String name) {
Bson filter = Filters.eq("name", name);
return getCollection().find(filter).first();
}
public Iterable<Person> findAll() {
final FindIterable<Person> iterable = getCollection().find();
return StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
}
public HttpResponse<Person> save( Person person) {
getCollection().insertOne(person);
return HttpResponse.created(person);
}
"/{name}") (
public HttpResponse delete(String name) {
Bson filter = Filters.eq("name", name);
getCollection().deleteOne(filter);
return HttpResponse.noContent();
}
private MongoCollection<Person> getCollection() {
return mongoClient
.getDatabase("main")
.getCollection("people", Person.class);
}
}
The application is ready to go, and you can run the test the application. The next step is to move to the cloud with Platform.sh.
- To move your application to the cloud, briefly, you need three files:
xxxxxxxxxx
"https://{default}/":
type upstream
upstream"app:http"
"https://www.{default}/"
type redirect
to"https://{default}/"
Platform.sh allows you to completely define and configure the topology and services you want to use on your project.
xxxxxxxxxx
mongodb
type mongodb3.6
disk1024
One containers (.platform.app.yaml). You control your application and the way it will be built and deployed on Platform.sh via a single configuration file. On this application, we allow the relationship between the PostgreSQL database and the application. So, our application container will have access to see the PostgreSQL container. Also, we'll overwrite the local configuration to use in the cloud to Platform.sh.
xxxxxxxxxx
name app
type"java:11"
disk1024
hooks
build mvn clean package -DskipTests
relationships
mongodb'mongodb:mongodb'
web
commands
start java -jar $JAVA_OPTS target/mongodb-0.1.jar
To simplify the application file, we'll use Shell variables int the .environment
file.
xxxxxxxxxx
export MONGO_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].port"`
export MONGO_HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].host"`
export MONGO_PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].password"`
export MONGO_USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].username"`
export MONGO_DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].path"`
export MONGO_URL=mongodb://${MONGO_USER}:${MONGO_PASSWORD}@${MONGO_HOST}:${MONGO_PORT}/${MONGO_DATABASE}
export JAVA_MEMORY=-Xmx$(jq .info.limits.memory /run/config.json)m
export JAVA_OPTS="$JAVA_MEMORY -XX:+ExitOnOutOfMemoryError"
The application is now ready, so it’s time to move it to the cloud with Platform.sh using the following steps:
- Create a new free trial account.
- Sign up with a new user and password, or login using a current GitHub, Bitbucket, or Google account. If you use a third-party login, you’ll be able to set a password for your Platform.sh account later.
- Select the region of the world where your site should live.
- Select the blank template.
You have the option to either integrate to GitHub, GitLab, or Platform.sh will provide to you. Finally, push to the remote repository.
Done! We have a simple and nice Micronaut application ready to go to the cloud.