Home Web Development Building Microservices with Micronaut®

Building Microservices with Micronaut®

By Nirmal Singh , Zack Dawood
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99 $32.98
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99 $32.98
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Getting Started with Microservices Using the Micronaut Framework
About this book
The open source Micronaut® framework is a JVM-based toolkit designed to create microservices quickly and easily. This book will help full-stack and Java developers build modular, high-performing, and reactive microservice-based apps using the Micronaut framework. You'll start by building microservices and learning about the core components, such as ahead-of-time compilation, reflection-less dependency injection, and reactive baked-in HTTP clients and servers. Next, you will work on a real-time microservice application and learn how to integrate Micronaut projects with different kinds of relational and non-relational databases. You'll also learn how to employ different security mechanisms to safeguard your microservices and integrate microservices using event-driven architecture in the Apache Kafka ecosystem. As you advance, you'll get to grips with automated testing and popular testing tools. The book will help you understand how you can easily handle microservice concerns in Micronaut projects, such as service discovery, API documentation, distributed configuration management, fallbacks, and circuit breakers. Finally, you'll explore the deployment and maintenance aspects of microservices and get up to speed with the Internet of Things (IoT) using the Framework. By the end of this book, you'll be able to build, test, deploy, and maintain your own microservice apps using the framework.
Publication date:
September 2021
Publisher
Packt
Pages
362
ISBN
9781800564237

 

Chapter 1: Getting Started with Microservices Using the Micronaut Framework

In recent times, there's been a good buzz about microservices and how the microservices architecture has been transformational in developing rapid, agile, and enterprise-grade web services to address the unique challenges and requirements of today's world. The microservices architecture has turned the page toward disciplining the standards on developing these web services. In this chapter, we will walk through the evolution of web services to microservices. We will quickly dive into some useful microservices design patterns. We will zero in on the key pitfalls in most of the traditional Java development frameworks and how their surface-level adoption to the microservices architecture has elevated performance and optimization issues. We will then explore how the Micronaut framework has addressed these performance and optimization issues in the microservices with an overhauled and ground-up approach to microservices development. Lastly, to get started with the Micronaut framework, we will set up the Micronaut CLI and work on a small hello world project.

In this chapter, we will focus on these topics in particular:

  • Introducing microservices and their evolution
  • Understanding microservices design patterns
  • Why Micronaut is the best choice for developing microservices
  • Getting started with the Micronaut framework
  • Working on the hello world project in the Micronaut framework

By the end of this chapter, you will have an understanding of how web services evolved in to microservices and why traditional Java frameworks are ineffective for developing microservices as compared to the Micronaut framework. Furthermore, we will also gain the practical knowledge to start using the Micronaut framework by working on a small project in the Micronaut framework.

 

Technical requirements

All the commands and technical instructions in this chapter are run on Windows 10 and mac OS X. Code examples covered in this chapter are available in the book's GitHub repository at https://github.com/PacktPublishing/Building-Microservices-with-Micronaut/tree/master/Chapter01.

The following tools need to be installed and set up in the development environment:

  • Java SDK: Version 13 or above (we used Java 14).
  • Maven: This is optional and only required if you would like to use Maven as the build system. However, we recommend having Maven set up on any development machine. Instructions to download and install Maven can be found at https://maven.apache.org/download.cgi.
  • Development IDE: Based on your preferences, any Java-based IDE can be used, but for the purpose of writing this chapter, IntelliJ was used.
  • Git: Instructions to download and install Git can be found at https://git-scm.com/downloads.
 

Introducing microservices and their evolution

Before we thoroughly jump into introducing and defining microservices, it will be helpful to know how microservices have evolved. In the late 1960s, Alan Kay coined the term object-oriented programming. Though it was a definitive idea, later it birthed the four pillars for building software solutions using object-oriented programming:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

In a short mnemonic, it's known as EIPA. Since the inception of these four pillars, the software industry has seen the rise and fall of many programming languages, frameworks, design patterns, and so on. With each such adaption and idea, thinkers and tinkerers have tried to come closer to EIPA by keeping a modular design and loosely coupled yet tightly encapsulated application components. Over the last few decades, software teams have moved away from the art of object-oriented programming toward the science of object-oriented programming by systematically adopting these key pillars. This iterative journey is the evolution of microservices.

In the late 1980s and early 1990s, almost every enterprise application was exposed as either a command line or native desktop software. Applications were tightly connected to databases and it was almost as if the end user was directly interacting with the database with the application as a thin façade in between. It was the era of monolithic applications or client/server architecture.

In the proceeding diagram, we can see how users interacted with a monolith application:

Figure 1.1 – Monolithic client/server architecture

Figure 1.1 – Monolithic client/server architecture

As depicted in Figure 1.1, in monolithic client/server architecture, the application is tightly coupled to the database and the user interacts through a terminal façade or desktop application. In this architecture, it was painful to maintain good service-level agreements (SLAs). Almost all the key non-functional factors such as scalability, high availability, fault tolerance, and flexibility underperformed or failed.

To address some of these aspects service-oriented architecture (SOA) came into existence. In the 2000s, SOA was formalized in the industry with the definition of some standard protocols such as Simple Object Access Protocol (SOAP). Web Services Description Language (WSDL) was also created during this period. Web 2.0 applications were popular with Asynchronous JavaScript And XML (AJAX). Enterprise service bus and messaging systems were highly used in enterprise applications. Advancements in SOA catalyzed a new paradigm of delivering software solutions to end users: Software as a Service (SaaS). Instead of desktop applications and terminal clients, software solutions were delivered to end users over HTTP as hosted online services. In the proceeding diagram, we can see how users interacted with an SOA-based application:

Figure 1.2 – SOA

Figure 1.2 – SOA

As shown, SOA brought in some decoupling by separating the concerns between the web application, web server, and app server. App servers or enterprise service buses (ESBs) usually interact with the database and the user interacts with the application by accessing it on web browsers (SaaS solutions). Though SOA brought some relief, the adoption of SaaS left scalability and flexibility as key unhashed puzzles.

Post-2010, the technology world started to move much faster than it did in the previous two decades. With the introduction of containers, the cloud, big data, and machine learning, everything started moving rapidly in architecture design. It is the era of Uber, Airbnb, Netflix, and freemium/premium applications. Applications are designed for distributed computing and scalability. With the microservices architecture, the application is decomposed to loosely coupled microservices where each microservice owns its database. In the proceeding diagram, we can see how users interact with a microservices-based application:

Figure 1.3 – Microservices architecture

Figure 1.3 – Microservices architecture

In the previous diagram, we can see a fully realized microservices application where each microservice interacts with and owns its database. The user interacts with a single-page application through a modern browser. Any incoming requests from the web server are routed to the respective microservice. The full realization of microservices architecture is to address key factors of scalability, fault tolerance, high availability, and flexibility.

To put it simply, microservices or microservices architecture componentize an application into a collection of interacting services. Each service could be developed, tested, deployed, and maintained independently. Thus, each smaller (micro) service has its own unique life cycle. Furthermore, since each service is loosely coupled (interacting with other services using HTTP/HTTPS), we can do the following:

  • Scale up or scale down (based on the service traffic).
  • Address any runtime faults (boot up the service backup).
  • Make new changes (change impact is limited to the service).

Therefore, through the complete realization of decoupled architecture in the microservices, we address key issues of scalability, fault tolerance, high availability, and flexibility.

So far, we have learned about microservices and their evolution and how they have been transformational in addressing the unique, rapid, and agile needs of today's world. This understanding is a good preface to realizing the potential of microservices. In the next section, we will dive into the microservices design patterns.

 

Understanding microservices design patterns

To fully realize the benefits of any architecture (including the microservices architecture), an architectural approach is often backed with design patterns. Understanding these design patterns is crucial for an ideal adoption of the architecture. In the following sections, we will cover some practical and commonly used design patterns in microservices. Each pattern addresses a different aspect of the application development life cycle and our focus would be to see these design patterns from a practical usage standpoint. We will begin with decomposition design patterns.

Decomposition design patterns

Decomposition design patterns dictate how we can componentize or decompose a big/monolithic application into smaller (micro) services. These patterns come in handy in designing a transformational architecture for any legacy monolithic application. The following are the most commonly used design patterns in decompositions.

Decomposing by business capability

Any business capability is an instrument to make a profit. If we can enlist and categorize an application into a set of business capabilities such as inventory management, customer orders, or operations, then the application can be decomposed into microservices that are based on these business capabilities. This process to decompose is effective and recommended for small- to medium-sized applications.

Decomposing by domains/sub-domains

If the application is an enterprise-grade and heavy application, then the previous approach may end up decomposing the application into smaller monoliths. These monoliths are smaller but monoliths nonetheless. In such cases, business modeling can help to categorize and map application functionalities into domains and sub-domains. Functionalities inside a domain/sub-domain are similar but very different from the functionalities of other domains/sub-domains. Microservices then can be designed and built around domains or sub-domains (if there are many functionalities mapped to a domain).

Integration design patterns

Once the application is broken down into smaller (micro) services, we will need to establish cohesion among these services. Integration design patterns address such collaboration requirements. The following are the most commonly used design patterns in integrations.

The API gateway pattern

Often upstream frontend consumers need to access microservices through a façade. This façade is called an API gateway. The API gateway design pattern serves an important purpose to keep things simple for frontend clients:

  • The frontend client is not sending too many requests to microservices.
  • The frontend client is not processing/aggregating too many responses (from microservices).
  • At the server end, the gateway routes a request to multiple microservices, and these microservices can run in parallel.
  • Before sending the final response, we can aggregate individual responses from different microservices.

The aggregator pattern

This pattern is very similar to the aforementioned API gateway pattern. However, composite microservice is the key differential. The mandate of a composite microservice is to offload an incoming request to multiple microservices and then collaborate to create a unified response. This pattern is used when a user request is atomic from business logic standpoints, but it is processed by multiple microservices.

The chained microservices pattern

In some scenarios, an incoming request is executed in a series of steps wherein each step could be spinning off a call to a microservice. For example, ordering an item in an online marketplace would require the following:

  1. Searching for an item (inventory management service)
  2. Adding an item to the cart (cart service)
  3. Checking out the added item (payment service, mail service, inventory management service)

All these service calls would be synchronous. Fulfilling a user request would be an amalgamation of all these chained microservice calls.

Data management patterns

Integrating with the persistence layer is an important aspect of any microservice-based application. Greenfield (net new) and brownfield (legacy transformation) applications may dictate their requirements in how to choose a data management pattern. The following are the most often used design patterns in data management in microservices.

Database per service

In greenfield (net new) applications, it is ideal to have a database per service. Each service is the owner of an isolated database (relational or non-relational) and any data operation must be executed through the microservice only. Furthermore, even if any other microservice needs to perform a database operation, then it should be routed through the owner microservice.

Shared database

In brownfield (transformational) applications, it may not be practical to decompose the database into one database per service. In such scenarios, the microservices architecture realization can be kickstarted with services sharing a common monolith database.

Command query responsibility segregation (CQRS)

In greenfield or fully transformed applications where each microservice is an independent database owner, there might be a requirement to query data from multiple databases. The CQRS pattern stipulates to decompose an application into a command and query:

  • Command: This part will manage any create, update, and delete requests.
  • Query: This part will manage query requests using database views where database views can unify data from multiple schemas or data sources.

Cross-cutting patterns

Some concerns cut across all the different aspects/layers of microservices. In the following sub-sections, we will discuss some of these concerns and patterns.

The service discovery pattern

In a microservices-based application, each microservice may have more than one instance at runtime. Furthermore, these service instances can be added or removed at runtime based on traffic. This runtime agility can be an issue for upstream consumers in how they connect with services.

The service discovery pattern addresses this by implementing a service registry database. The service registry is a metadata store containing information such as the service name, where the service is running, and the current status of the service. Any change to the service runtime information will be updated in the service registry, for example, when a service adds a new instance or a service is down. This eases the pain for upstream consumers to connect with different microservices in the application.

The circuit breaker pattern

In a microservices-based application, often services interact with each other by invoking endpoints. There could be a scenario where a service is calling a downstream service but the downstream service is down. Without a circuit breaker, the upstream service will keep calling the downstream service while it's down and this will keep impacting the user interaction with the application.

In the circuit breaker pattern, a downstream service call will be routed through a proxy. This proxy will timeout for a fixed interval if the downstream service is down. After the timeout expiry, the proxy will try to connect again. If successful, it will connect with the downstream service; otherwise, it will renew the timeout period. Therefore, the circuit breaker will not bombard the downstream service with unnecessary calls and it will not impact user interaction with the application.

The log aggregation pattern

In the microservices landscape, often an incoming request will be processed by multiple services. Each service may create and log its entries. To trace any issues, it will be counter-intuitive to access these sporadic logs. By implementing a log aggregation pattern, logs could be indexed in a central place, thereby enabling easy access to all application logs. Elasticsearch, Logstash, Kibana (ELK) can be used to implement log aggregation.

In this section, we covered some often-used design patterns in different stages of the application life cycle. Understanding these design patterns is required to fully reap the benefits of microservices architecture. In the next section, we will dive into the Micronaut framework for developing microservices.

 

Why Micronaut is the best choice for developing microservices

In the previous sections, we learned about the maturity on the architectural side of microservices. Unfortunately, on the implementation side, an overhaul shift to build/develop microservices is not as mature as microservices architecture. To address some of these implementation challenges, many traditional Java frameworks have added small, iterative changes, but much-sought-after disruptive and overhauled changes are missing. At the core, these traditional Java frameworks have stayed almost the same since the time of monolithic services. Reflections, runtime proxies, and bulky configuration management have plagued all traditional frameworks with slower boot time and bigger memory footprints, making them unsuitable for microservices development.

Micronaut is developed from the bottom up, considering these important challenges, to organically support microservices development:

  • Dependency injection: Micronaut uses JSR-330 @Inject for dependency injection. It adds the Java inject module to the compiler and all the annotations are processed at compile time. The compiler generates the byte code for all the classes based on the annotations that are used in their source code. This is all done at compile time. At runtime, Micronaut can instantiate the beans and read their metadata from the generated byte code and does not need to use the slow reflection API.
  • Ahead-of-time compilation: As discussed before, one of the key contrasts is that Micronaut performs dependency injection, configuration management, and aspect-oriented programming proxying at compile time. Micronaut relies on one or more annotation processors to process the annotation metadata into ASM-generated (assembly) byte code. Furthermore, this ahead-of-time-generated byte code is further optimized by Java's just-in-time (JIT) compiler. Other frameworks use reflection and produce the annotation metadata at application boot-up. This metadata is loaded to runtime memory, therefore increasing the memory footprint. Instead of the Java Reflection API, Micronaut uses the Java annotation processor API, the Kotlin compiler plugin for annotation processors, and Groovy AST transformations for metaprogramming.
  • Faster boot-up time and lower memory consumption: Other frameworks use Java reflections and at application boot-up, all classpaths are scanned to generate reflection metadata for each field, method, and constructor. This metadata is then used to determine and inject the required object into the application runtime. This adds significantly to boot-up time as well as runtime memory. As discussed previously, Micronaut uses ahead-of-time compilation and the Java annotation processor API to offload such work from the runtime and reduce memory requirements by not pushing unnecessary reflection metadata onto runtime memory.
  • Serverless applications support: One of the key issues in serverless applications is boot-up time. With a huge memory footprint and slower boot-up time, traditional frameworks are not a prudent choice to develop serverless applications. Micronaut organically supports serverless application development by keeping the minimal runtime memory footprint and sub-second boot-up time. Furthermore, Micronaut natively supports commonly used cloud platforms for serverless function development.
  • Language-agnostic framework: The Micronaut framework supports the Java, Kotlin, and Groovy programming languages. With varied support for major programming languages, developers can choose their preferred language option when considering cloud requirements. For example, for IoT requirements, Groovy could be a good option. This language-agnostic enablement makes it flexible and apt for varied requirements of mobile/web/cloud solutions.
  • Support to GraalVM: Since Micronaut doesn't use reflections, any Micronaut-based application can be ahead-of-time compiled into a GraalVM native image. GraalVM is a universal virtual machine offered by Oracle that can run a Java application down to machine code. This increases application performance significantly. Any Micronaut application compiled to a GraalVM native image can boot up in milliseconds.

In light of the preceding key points, Micronaut stands out as a preferred framework to develop cloud-native, ultra-light, and rapid microservices. In addition, we performed a quick benchmark experiment to compare the application startup times for Micronaut versus another popular traditional framework. In the following chart, startup times are shown for both Micronaut and a traditional framework:

Figure 1.4 – Startup times for a traditional framework versus Micronaut

Figure 1.4 – Startup times for a traditional framework versus Micronaut

As shown in the preceding chart, the traditional framework took 6,156 milliseconds to boot up whereas Micronaut took only 3,750 milliseconds. This time difference in booting up the application is significant and sets Micronaut as a go-to framework for developing cloud-native and rapid microservices.

In the following section, we will get started with using the Micronaut framework on both Windows as well as mac OS.

 

Getting started with the Micronaut framework

In order to get started with the Micronaut framework, we will begin by installing the Micronaut CLI on Mac and Windows OS.

Installing the Micronaut CLI on mac OS

On mac OS, we can install the Micronaut CLI in a couple of ways – using SDKMAN!, Homebrew, or MacPorts. In the following sections, we will cover step-by-step instructions to install the Micronaut CLI.

Installing Micronaut using SDKMAN!

Please follow these steps to install the Micronaut CLI using SDKMAN!:

  1. Open Terminal.
  2. If you don't have SDKMAN! installed, take the following steps:

    a. Type or paste the following command:

    curl -s https://get.sdkman.io | bash

    b. Next, type or paste the following command:

    source "$HOME/.sdkman/bin/sdkman-init.sh"
  3. To install the Micronaut CLI, type or paste the following command:
    source sdk install micronaut

    You will observe the following interactions on Terminal while installing the Micronaut CLI:

    Figure 1.5 – Installing Micronaut CLI on mac OS using SDKMAN!

    Figure 1.5 – Installing Micronaut CLI on mac OS using SDKMAN!

  4. If all the preceding steps execute successfully, you can verify the Micronaut CLI installation by running the following command in Terminal:
    mn -version

Installing Micronaut using Homebrew

Please follow these steps to install the Micronaut CLI using MacPorts:

  1. Open Terminal.
  2. If you don't have Homebrew installed, then take the following steps:

    a. Type or paste the following command:

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

    b. Next, type or paste the following command:

    brew update 
  3. Type or paste the following command:
     brew install micronaut

    You will observe the following interactions on Terminal while installing the Micronaut CLI:

    Figure 1.6 – Installing the Micronaut CLI on mac OS using HomeBrew

    Figure 1.6 – Installing the Micronaut CLI on mac OS using HomeBrew

  4. If all the preceding steps execute successfully, you can verify the Micronaut CLI installation by hitting the following command in Terminal:
    mn -version

Installing Micronaut using MacPorts

Please follow these steps to install the Micronaut CLI using Homebrew:

  1. If you don't have MacPorts installed, then follow the instructions at https://www.macports.org/install.php.
  2. Open Terminal.
  3. Type or paste the following command:
    sudo port sync
  4. Type or paste the following command:
    sudo port install micronaut

    You will observe the following interactions on Terminal while installing the Micronaut CLI:

    Figure 1.7 – Installing the Micronaut CLI on macOS using MacPorts

    Figure 1.7 – Installing the Micronaut CLI on macOS using MacPorts

  5. If all the preceding steps execute successfully, you can verify the Micronaut CLI installation by hitting the followed command in Terminal:
    mn -version

Installing the Micronaut CLI on Windows

Please follow these steps to install the Micronaut CLI on Windows:

  1. Download the Micronaut CLI binary from the Micronaut download page: https://micronaut.io/download.html.
  2. Unzip the downloaded binary file into a folder on your system. It is better to keep this in a separate folder under a root directory such as C:\Program Files\Micronaut.
  3. Create a new system variable called MICRONAUT_HOME with the preceding directory path. Please note to add this variable under system variables (not user variables).
  4. Then, update your Windows PATH environment variable. You can add a path such as %MICRONAUT_HOME%\bin.
  5. Open Command Prompt or any terminal and type the following command:
    mn

    This will boot up the CLI for the first time by resolving any dependencies.

  6. To test that the CLI is installed properly, type the following command:
    mn – h

    This is what the command outputs:

    Figure 1.8 – Installing the Micronaut CLI on Windows OS

    Figure 1.8 – Installing the Micronaut CLI on Windows OS

  7. You should see all the CLI options after hitting the preceding command.

In this section, we explored different ways to install the Micronaut CLI in Windows and macOS. In order to get hands-on with the Micronaut framework, we will get started with working on a hello world project in the next section.

 

Working on a hello world project in the Micronaut framework

To understand the practical aspects of using the Micronaut framework for developing a microservice, we will work with a hello world project. This will help you quickly get started with the Micronaut framework and also give you first-hand experience of how easy it is to do microservices development.

Micronaut works seamlessly with the Maven and Gradle packaging managers. We will cover one example for each using the Micronaut CLI as well as Micronaut Launch (web interface) for generating barebones projects.

Creating a hello world project using the Micronaut CLI

Please take the following steps to create a hello world application using the Micronaut CLI:

  1. Open the terminal (or Command Prompt).
  2. Change the directory to your desired directory where you want to create the hello world project.
  3. Type the following command:
    mn create-app hello-world-maven --build maven
  4. Wait for the Micronaut CLI to finish and it will create a hello-world-maven project. The create-app command will create a boilerplate project for you with a Maven build and your system-installed Java version. It will create Application.java as well as a sample test class called ApplicationTest.java.
  5. To explore your freshly created hello-world-maven project, open this project in your preferred IDE.
  6. To run your project, run the following command in a Bash terminal:
    ./mvnw compile exec:exec

    Please note that if you are copying the project from somewhere else, then it's required to regenerate mvnw by typing the following command:

    mvn -N io.takari:maven:wrapper
  7. The Maven wrapper will build and run your project on http://localhost:8080 by default.

Adding HelloWorldController

To create a simple endpoint, let's add a simple controller to the hello-world-maven project:

  1. Add a web package to our hello-world-maven project.
  2. Add a HelloWorldController Java class. It will contain a simple hello endpoint:
    @Controller("/hello")
    public class HelloController {
        @Get("/")
        @Produces(MediaType.TEXT_PLAIN)
        public String helloMicronaut() {
            return "Hello, Micronaut!";
        }
    }

    HelloController is accessible on the …/hello path. helloMicronaut() will generate a plain text "Hello, Micronaut!" message.

  3. Rerun your application and hit http://localhost:8080/hello/ in a browser window. The server will return the following response:
Figure 1.9 – Hello, Micronaut!

Figure 1.9 – Hello, Micronaut!

By default, the application will be accessible on port 8080, and this port can be changed in the application properties.

So far, we have worked on a hello world project using the Micronaut CLI. Next, we will explore Micronaut Launch, which is a web interface, to generate a boilerplate project.

Creating a hello world project using Micronaut Launch

Micronaut Launch (https://micronaut.io/launch/) is an intuitive web interface that came into existence with Micronaut 2.0.1. We can use this interface to quickly generate boilerplate for different kinds of Micronaut applications (such as server applications, the CLI, serverless functions, a messaging application, and so on). Let's quickly use this to generate a hello world application for us.

Please follow these instructions to generate the hello world project using the Micronaut Launch web interface:

  1. Open Micronaut Launch in a browser window: https://micronaut.io/launch/.
  2. Under Application Type, choose Application.
  3. Under Micronaut Version, choose 2.0.1.
  4. For the Java version, choose Java 14.
  5. For Language, choose Java.
  6. Give a base package name such as com.packtpub.micronaut.
  7. Choose Gradle as the build option.
  8. Give a name to the application, such as hello-world-gradle.
  9. Choose JUnit as the testing framework
  10. After you've finished choosing all the options, click on GENERATE PROJECT.

After choosing the preceding options and providing various inputs, the Micronaut Launch interface should look as follows:

Figure 1.10 – Using Micronaut Launch to generate a boilerplate project

Figure 1.10 – Using Micronaut Launch to generate a boilerplate project

Your project boilerplate source code will be generated into a zipped file. You can unarchive this zipped file into your desired directory and open it in your preferred IDE. Just like the previous example (hello-world-maven), we can add a basic HelloWorldController instance.

To run your project, run the following command in a Bash terminal:

gradlew.bat run

When the project is running, go to http://localhost:8080/hello and you should see the Hello, Micronaut! message in the browser tab.

In this section, we explored how to get started with the Micronaut framework by developing small hello world projects using the Micronaut CLI as well as the Micronaut Launch user interface. This small exercise will be a good preface for what we will cover in the next chapter.

 

Summary

In this chapter, we began our journey into microservices by exploring their evolution and some useful design patterns. We covered the Micronaut framework in contrast to the traditional reflection-based Java frameworks. Essentially, Micronaut's approach to leverage ahead-of-time compilation (and not reflections) sets it apart as an ideal framework for developing microservices. To get our hands dirty, we went through setting up the Micronaut CLI on mac OS as well as Windows OS. Lastly, we worked on hello-world-maven and hello-world-gradle projects. In both projects, we added hello endpoints.

With the fundamentals of microservices as well as practical hello world projects covered, this chapter enhanced your knowledge of the evolution of microservices, their design patterns, and why Micronaut should be preferred for developing microservices. This foundational understanding is the bedrock for starting the adventure of microservices development in the Micronaut framework.

At the end of this chapter, we kickstarted an exciting journey into microservices development using the Micronaut CLI and Micronaut Launch. In the next chapter, we will explore how we can integrate different kinds of persistent storage and databases in the Micronaut framework.

 

Questions

  1. How did web services evolve into microservices?
  2. What is a microservice?
  3. What is the microservice architecture?
  4. What are the microservices design patterns?
  5. What is Micronaut?
  6. Why should Micronaut be preferred for developing microservices?
  7. Which framework should be used to develop microservices?
  8. How do you install the Micronaut CLI on macOS?
  9. How do you install the Micronaut CLI on Windows OS?
  10. How do you create a project using the Micronaut CLI?
  11. How do you create a project using Micronaut Launch?
About the Authors
  • Nirmal Singh

    Nirmal Singh is entrepreneurial-spirited and a renaissance mind technology leader, with 10+ years of broad and unique cross-domain experience in handling complex inter-disciplinary requirements and leading high performing software development teams and delivering robust software solutions. He has worked in various techno-functional roles, serving health-tech, fin-tech, retail and social commerce verticals in both the product and consulting engagements. He is currently leading a product engineering group at CGI to re-engineer a classic mission critical wealth application.

    Browse publications by this author
  • Zack Dawood

    Mohammed Zackria Arshid is an Award Winning Speaker, Technologist, and Leader. He has 15+ Years of Experience in IT Software Product Development, BigData, Machine Learning, Mobile Apps, Blockchain, Payments, Agile Transformation, and Enterprise Architecture. He has worked in 13 countries across Europe, North America and Asia. He has done vaious certifications in Oracle Certified Professional, Java SE6 Programmer, Oracle PL/SQL Developer Certified Associate, IBM Certified Database Associate- DB2 Fundamentals, IBM Certified Academic Associate and IBM Certified Associate Developer- RAD for WebSphere V6.

    Browse publications by this author