Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Building Microservices with Micronaut®
Building Microservices with Micronaut®

Building Microservices with Micronaut®: A quick-start guide to building high-performance reactive microservices for Java developers

Arrow left icon
Profile Icon Singh Profile Icon Zack Dawood
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7 (7 Ratings)
Paperback Sep 2021 362 pages 1st Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Singh Profile Icon Zack Dawood
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7 (7 Ratings)
Paperback Sep 2021 362 pages 1st Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Building Microservices with Micronaut®

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?
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to build scalable, fast, and resilient microservices with this concise guide
  • Explore the many advantages of using reflection-free, compile-time dependency injections and aspect-oriented programming
  • Build cloud-native applications easily with the Micronaut framework

Description

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.

Who is this book for?

This book is for developers who have been building microservices on traditional frameworks such as Spring Boot and are looking for a faster alternative. Intermediate-level knowledge of Java programming and implementing web services development in Java is required.

What you will learn

  • Understand why the Micronaut framework is best suited for building microservices
  • Build web endpoints and services in the Micronaut framework
  • Safeguard microservices using Session, JWT, and OAuth in Micronaut projects
  • Get to grips with event-driven architecture in Micronaut applications
  • Discover how to automate testing at various levels using built-in tools and testing frameworks
  • Deploy your microservices to containers and cloud platforms
  • Become well-versed with distributed logging, tracing, and monitoring in Micronaut projects
  • Get hands-on with the IoT using Alexa and the Micronaut framework

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 30, 2021
Length: 362 pages
Edition : 1st
Language : English
ISBN-13 : 9781800564237
Vendor :
Sun Microsystems
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 30, 2021
Length: 362 pages
Edition : 1st
Language : English
ISBN-13 : 9781800564237
Vendor :
Sun Microsystems
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 114.97
Building Microservices with Micronaut®
€41.99
Microservices with Spring Boot and Spring Cloud
€36.99
Designing Hexagonal Architecture with Java
€35.99
Total 114.97 Stars icon

Table of Contents

19 Chapters
Section 1: Core Concepts and Basics Chevron down icon Chevron up icon
Chapter 1: Getting Started with Microservices Using the Micronaut Framework Chevron down icon Chevron up icon
Section 2: Microservices Development Chevron down icon Chevron up icon
Chapter 2: Working on Data Access Chevron down icon Chevron up icon
Chapter 3: Working on RESTful Web Services Chevron down icon Chevron up icon
Chapter 4: Securing the Microservices Chevron down icon Chevron up icon
Chapter 5: Integrating Microservices Using Event-Driven Architecture Chevron down icon Chevron up icon
Section 3: Microservices Testing Chevron down icon Chevron up icon
Chapter 6: Testing Microservices Chevron down icon Chevron up icon
Section 4: Microservices Deployment Chevron down icon Chevron up icon
Chapter 7: Handling Microservice Concerns Chevron down icon Chevron up icon
Chapter 8: Deploying Microservices Chevron down icon Chevron up icon
Section 5: Microservices Maintenance Chevron down icon Chevron up icon
Chapter 9: Distributed Logging, Tracing, and Monitoring Chevron down icon Chevron up icon
Section 6: IoT with Micronaut and Closure Chevron down icon Chevron up icon
Chapter 10: IoT with Micronaut Chevron down icon Chevron up icon
Chapter 11: Building Enterprise-Grade Microservices Chevron down icon Chevron up icon
Assessment Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(7 Ratings)
5 star 28.6%
4 star 42.9%
3 star 14.3%
2 star 0%
1 star 14.3%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Nov 14, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a great start point for anyone who has some experience in Java web services and is looking for developing microservices skills.Coding along with the book is a journey building a hands-on project from scratch to a fully fledged application. A wide range of tools are introduced to address various concerns that get in our way.The writing and examples are all very clear, and there are plenty of diagrams and figures to help you understand. GitHub repo is also provided to help you follow along.This book equips you with skills to build an enterprise level microservices application, from design, development and testing to security, deployment and maintenance. If that's what you are looking for, you will get the most out of the book.To summarize, it's a great book to level up your microservices skills. If you are serious about building a project using Micronaut, definitely keep one within your reach.
Amazon Verified review Amazon
Faceless144p Aug 14, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
First sorry for my English, it is actually my third language. I am currently at the 3/4 of the book and I really like the way it is written. The code is available on a Github repository, witch make it way easier to follow the book while the author is implementing the 3 services. The most important concept are seen in details and other concepts are just brief introduction which is perfect (remember that it is a quick-start guide). For me this book is a 5 stars, I highly recommend it.
Amazon Verified review Amazon
Priya R Shastri Dec 15, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a quick start guide for developing microservices for Java developers.Micronaut is a JVM based framework for building lightweight modular applications. It is a fast growing framework designed to make creating microservices quick and easy. This book is a reference material for Java developers building services using Micronaut.In chapter 1 Understanding core concepts of microservices, the author uses block diagrams to describe the microservices design. Where to download the micronaut sdk is provided. In chapter 2 ORM framework is explained by the author. Micronaut Launch is described in this chapter. In chapter 3 working on RESTful services is described in detail. For a novice to REST services, this chapter is ideal. Endpoints are explained in this chapter. CRUD operations are explained in this chapter in addition to creation of endpoints.In chapter 4 Securing the Microservices is discussed. Session authentication, JWT authentication and OAuth authentication are discussed in detail here. Using Okta for mobile application authentication is described here. In chapter 5 Integrating microservices with event driven authentication is discussed. Event driven architechtures are crucial in determining the functioning of microservices. In chapter 6 Microservices testing is discussed as a top down pyramid with E2E serices testing, System testing followed by unit testing at the bottom. In chapter 7 Handling microservices concern, the author discusses configuration management, service discovery, API gateways and fault tolerance. A key benefit of implementing microservices is the fault tolerance. In chapter 8 Microservices deployment is discussed in detail. The block diagram for dockerization of containers is here.OverallThis book is great for explaining the architechture of microservices and entity relationshoip diagrams and block diagrams.The source code is provided in github.Can improve onProviding case studies (One case study is that of a pet-supply store chain)
Amazon Verified review Amazon
r.b. Nov 29, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book is mainly for someone who knows Java and wants to learn how to write Microservices using the popular framework Micronaut. This book will walk you through the development of a small pet clinic application composed of Microservices.Instead of deploying the entire application on some cloud, the authors kept the application independent of any specific cloud platform. The whole cluster of microservices can be deployed on Docker containers on a local PC. The cluster includes load balancers, microservices, databases, Kafka for stream processing, Elasticsearch, Logstash, Kibana, Zipkin, Prometheus, and Grafana for tracing and monitoring.It also covers IoT by walking readers through the development of an Alexa Skill.
Amazon Verified review Amazon
Jacob Mikkelsen Dec 05, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Micronaut is a wonderfull addition to microservice framework in the JAVA/Groovy/Kotlin ecosystem, with its low startup time, reduced memory usage and its flat learning curve. This book provides a good introduction to microservices with Micronaut, but also gives great instructions in how you can actually run those in production (logging, monitoring , etc.)I like that the book is thorough in its descriptions, both the background like microservice architecture and patters, and the technical aspects of implementing the solutions in the Micronaut framework. The book quickly moves past the "Hello world" examples and digs deep into topics like persistance of data, implementing RESTfull services, security and event-driven architecture.Building Microservices with Micronaut is a pleasant book to study. You can read parts of it, when you need to refresh fx how to test your microservice, or lookup sample configuration snippets and code snippets, or you can start from chapter 1 and get the full course. It is great that the full chapter examples are available in the Github repository that accompanies the book.I give this book 4 starts. The reason it does not get 5 stars is, it provides a solid basis for implementing microservices in Micronaut assuming you already know how to build web services in JAVA. With that knowledge, parts of the book becomes trivial and superficial. Including an Alexa skill is neat, but slightly irrelevant, and could have been replaced with more information on deployment and maintaining the services in cloud architecture (not just local docker-compose env.) Finally, the book and samples ignores other build systems (fx Gradle), programming languages (Groovy and Kotlin) and test frameworks (Spock).If you have not worked with Micronaut, this book is a good choice to get started. If you are considering microservice architecture and would like to "dip your toes", this book is for you.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.