{{announcement.body}}
{{announcement.title}}

Micronaut in the Cloud: Intro to MongoDB in Microservices

DZone 's Guide to

Micronaut in the Cloud: Intro to MongoDB in Microservices

In the fourth part of this series on deploying Micronaut to the cloud, we take a look at building the Micronaut app with MongoDB.

· Java Zone ·
Free Resource

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:

Shell
 




x


 
1
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.

YAML
 




xxxxxxxxxx
1


1
micronaut:
2
  application:
3
    name: mongodb
4
mongodb.uri: ${MONGO_URL:`mongodb://localhost:27017/database`}
5
 
          



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.

Java
 




x


 
1
import io.micronaut.core.annotation.Introspected;
2
import javax.validation.constraints.NotBlank;
3
 
          
4
@Introspected
5
public class Person {
6
 
          
7
    @NotBlank
8
    private String name;
9
 
          
10
    @NotBlank
11
    private String city;
12
 
          
13
    @NotBlank
14
    private String country;
15
 
          
16
   //getter and setter
17
}
18
 
          



The last step is to create a resource where the client can do the request and then the CRUD.

Java
 




x


 
1
import com.mongodb.client.FindIterable;
2
import com.mongodb.client.MongoClient;
3
import com.mongodb.client.MongoCollection;
4
import com.mongodb.client.model.Filters;
5
import io.micronaut.http.HttpResponse;
6
import io.micronaut.http.annotation.Body;
7
import io.micronaut.http.annotation.Controller;
8
import io.micronaut.http.annotation.Delete;
9
import io.micronaut.http.annotation.Get;
10
import io.micronaut.http.annotation.Post;
11
import org.bson.conversions.Bson;
12
 
          
13
import javax.validation.Valid;
14
import java.util.stream.Collectors;
15
import java.util.stream.StreamSupport;
16
 
          
17
@Controller("/people")
18
public class PersonController {
19
 
          
20
    private final MongoClient mongoClient;
21
 
          
22
    public PersonController(MongoClient mongoClient) {
23
        this.mongoClient = mongoClient;
24
    }
25
 
          
26
    @Get("/{name}")
27
    public Person show(String name) {
28
        Bson filter = Filters.eq("name", name);
29
        return getCollection().find(filter).first();
30
    }
31
 
          
32
    @Get
33
    public Iterable<Person> findAll() {
34
        final FindIterable<Person> iterable = getCollection().find();
35
        return StreamSupport.stream(iterable.spliterator(), false)
36
                .collect(Collectors.toList());
37
    }
38
 
          
39
    @Post
40
    public HttpResponse<Person> save(@Body @Valid Person person) {
41
        getCollection().insertOne(person);
42
        return HttpResponse.created(person);
43
    }
44
 
          
45
    @Delete("/{name}")
46
    public HttpResponse delete(String name) {
47
        Bson filter = Filters.eq("name", name);
48
        getCollection().deleteOne(filter);
49
        return HttpResponse.noContent();
50
    }
51
 
          
52
    private MongoCollection<Person> getCollection() {
53
        return mongoClient
54
                .getDatabase("main")
55
                .getCollection("people", Person.class);
56
    }
57
}
58
 
          



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:
YAML
 




xxxxxxxxxx
1


1
"https://{default}/":
2
  type: upstream
3
  upstream: "app:http"
4
 
          
5
"https://www.{default}/":
6
  type: redirect
7
  to: "https://{default}/"
8
 
          



Platform.sh allows you to completely define and configure the topology and services you want to use on your project.

YAML
 




xxxxxxxxxx
1


 
1
mongodb:
2
  type: mongodb:3.6
3
  disk: 1024



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.

YAML
 




xxxxxxxxxx
1
10


 
1
name: app
2
type: "java:11"
3
disk: 1024
4
hooks:
5
    build: mvn clean package -DskipTests
6
relationships:
7
    mongodb: 'mongodb:mongodb'
8
web:
9
    commands:
10
        start: java -jar $JAVA_OPTS target/mongodb-0.1.jar



To simplify the application file, we'll use Shell variables int the  .environment  file.

Shell
 




xxxxxxxxxx
1


1
export MONGO_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].port"`
2
export MONGO_HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].host"`
3
export MONGO_PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].password"`
4
export MONGO_USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].username"`
5
export MONGO_DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|jq -r ".mongodb[0].path"`
6
export MONGO_URL=mongodb://${MONGO_USER}:${MONGO_PASSWORD}@${MONGO_HOST}:${MONGO_PORT}/${MONGO_DATABASE}
7
export JAVA_MEMORY=-Xmx$(jq .info.limits.memory /run/config.json)m
8
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.



Topics:
cloud (add topic), java, micronaut, mongodb, nosql, paas, platform.sh

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}