DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Cost Optimization Strategies for Managing Large-Scale Open-Source Databases
  • Schema Change Management Tools: A Practical Overview
  • Which Tool Is Better for Code Completion — Azure Data Studio or dbForge SQL Complete?
  • Application Assessment Questions for Migration Projects

Trending

  • Simplifying Multi-LLM Integration With KubeMQ
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • Navigating Change Management: A Guide for Engineers
  • Integration Isn’t a Task — It’s an Architectural Discipline
  1. DZone
  2. Data Engineering
  3. Databases
  4. Micronaut in the Cloud: Micronaut Data

Micronaut in the Cloud: Micronaut Data

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

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Jul. 09, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
8.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

The tutorial of the second tutorial about Micronaut in the cloud we'll deploy an application with Micronaut Data. Micronaut Data is a database access toolkit that uses Ahead of Time (AoT) compilation to pre-compute queries for repository interfaces that are then executed by a thin, lightweight runtime layer.

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 Postgresql and Micronaut Data dependency.

If you want to run a PostgreSQL locally, a good option might be Docker, which you can run with the command below:

Shell
 




xxxxxxxxxx
1


 
1
docker run --ulimit memlock=-1:-1 -it --rm=true --memory-swappiness=0 --name micronaut_test -e POSTGRES_USER=micronaut -e POSTGRES_PASSWORD=micronaut -e POSTGRES_DB=micronaut -p 5432:5432 postgres:10.5


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
11


 
1
micronaut:
2
  application:
3
    name: jpa
4
datasources:
5
  default:
6
    url: ${JDBC_URL:`jdbc:postgresql://localhost:5432/micronaut`}
7
    driverClassName: org.postgresql.Driver
8
    username: ${JDBC_USER:micronaut}
9
    password: ${JDBC_PASSWORD:micronaut}
10
jpa.default.properties.hibernate.hbm2ddl.auto: update
11

          


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 books. Therefore, we'll create a Book entity.

Java
 




x


 
1
import javax.persistence.Column;
2
import javax.persistence.Entity;
3
import javax.persistence.GeneratedValue;
4
import javax.persistence.GenerationType;
5
import javax.persistence.Id;
6
import javax.persistence.Table;
7
import javax.validation.constraints.NotNull;
8
import java.util.Objects;
9

          
10
@Entity
11
@Table(name = "book")
12
public class Book {
13

          
14

          
15
    @Id
16
    @GeneratedValue(strategy = GenerationType.AUTO)
17
    private Long id;
18

          
19
    @NotNull
20
    @Column(name = "name", nullable = false)
21
    private String name;
22

          
23
    @NotNull
24
    @Column(name = "isbn", nullable = false)
25
    private String isbn;
26

          
27
 //getter and setter
28
}


In a database integration, we're happy to have a CrudRepository. It is an interface for performing CRUD (Create, Read, Update, Delete). This a blocking variant and is based mainly on the same interface in Spring Data; however, it includes integrated validation support.

Java
 




xxxxxxxxxx
1


 
1
import io.micronaut.data.annotation.Repository;
2
import io.micronaut.data.repository.CrudRepository;
3

          
4
@Repository
5
public interface BookRepository extends CrudRepository<Book, Long> {
6
}
7

          



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

Java
 




x


 
1
import io.micronaut.http.HttpResponse;
2
import io.micronaut.http.annotation.Body;
3
import io.micronaut.http.annotation.Controller;
4
import io.micronaut.http.annotation.Delete;
5
import io.micronaut.http.annotation.Get;
6
import io.micronaut.http.annotation.Post;
7
import io.micronaut.scheduling.TaskExecutors;
8
import io.micronaut.scheduling.annotation.ExecuteOn;
9

          
10
import javax.validation.Valid;
11

          
12
@ExecuteOn(TaskExecutors.IO)
13
@Controller("/books")
14
public class BookController {
15

          
16
    private final BookRepository repository;
17

          
18
    public BookController(BookRepository repository) {
19
        this.repository = repository;
20
    }
21

          
22
    @Get("/{id}")
23
    public Book show(Long id) {
24
        return repository.findById(id).orElse(null);
25
    }
26

          
27
    @Get
28
    public Iterable<Book> findAll() {
29
        return repository.findAll();
30
    }
31

          
32
    @Post
33
    public HttpResponse<Book> save(@Body @Valid Book book) {
34
        return HttpResponse.created(repository.save(book));
35
    }
36

          
37
    @Delete("/{id}")
38
    public HttpResponse delete(Long id) {
39
        repository.deleteById(id);
40
        return HttpResponse.noContent();
41
    }
42

          
43
}
44

          



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}/"



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

YAML
 




xxxxxxxxxx
1


 
1
db:
2
  type: postgresql:11
3
  disk: 512



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
    database: "db:postgresql"
8
web:
9
    commands:
10
        start: java -jar $JAVA_OPTS target/micronaut-data-0.1.jar


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

Shell
 




xxxxxxxxxx
1


 
1
export JDBC_HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].host"`
2
export JDBC_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].port"`
3
export JDBC_PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].password"`
4
export JDBC_USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].username"`
5
export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].path"`
6
export JDBC_URL=jdbc:postgresql://${JDBC_HOST}:${JDBC_PORT}/${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.

Cloud application Data (computing) Database

Opinions expressed by DZone contributors are their own.

Related

  • Cost Optimization Strategies for Managing Large-Scale Open-Source Databases
  • Schema Change Management Tools: A Practical Overview
  • Which Tool Is Better for Code Completion — Azure Data Studio or dbForge SQL Complete?
  • Application Assessment Questions for Migration Projects

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

OSZAR »