Skip to content

The Data Scientist

the data scientist logo
Micronaut microservices

Tutorial: Crafting Micronaut Microservices with MicrostarterCLI


Wanna become a data scientist within 3 months, and get a job? Then you need to check this out !

MicrostarterCLI serves as a swift development apparatus, empowering developers to swiftly conjure standard, reusable codes, configurations, and archetypes requisite for your application. In an antecedent exposition, I elucidated a rudimentary exemplar of fabricating REST and GraphQL endpoints within a Micronaut application.

This discourse delineates an instance of initializing a Micronaut microservices application utilizing MicrostarterCLI. The architecture of the application encapsulates the following components:

  1. Fruit Service: A rudimentary CRUD service catering to Fruit entities.
  2. Vegetable Service: A basic CRUD service designed for Vegetable entities.
  3. Eureka Service Discovery Server
  4. Consul Configuration Server
  5. Spring Cloud Gateway

Establishing the Environment

Start by downloading MicrostarterCLI version 2.5.0 or later.  Extract the zip archive, then adjust your system’s environment variables to include the appropriate directory. Subsequently, the mc.jar, mc.bat, and mc can be invoked from any location within the operating system.

To verify the installation, execute the following command in the command prompt:

mc --version

Environment Specifications:

  • Operating System: Windows 11
  • Java Version: 11
  • IDE: IntelliJ

Let’s Begin Development

Step 0: Create a Workspace Directory

Establish a folder on your system to house the projects. While optional, this practice facilitates organization. In this article, we’ll use c:workspace as our workspace directory.

Step 1: Create the Fruit Service

The FruitService is a straightforward service encompassing all CRUD operations to manage Fruit objects. For ease, we’ll utilize the H2 database. MicrostarterCLI will assist in generating all the necessary CRUD operation code and configurations as follows:

  • Generate a Micronaut Application:

Begin by generating a Micronaut application using Micronaut Launch. Extract the project zip file into the c:workspace folder. Alternatively, use the init command of MicrostarterCLI to directly generate the project from Micronaut Launch, as shown below:

mc init --name FruitService --package io.hashimati

  • Navigate to the FruitService Directory:

After running the init command, enter the FruitService directory. Execute the entity command to include the necessary dependencies, configure the service, and generate the required CRUD service code:

cd FruitService

mc entity -e Fruit

Answer Configuration Questions

After executing the mc entity -e Fruit command, MicrostarterCLI will prompt you with configuration questions. Provide the following responses:

OptionAnswerDescription
Is the application monolithic?noSpecifies whether the service is monolithic or microservice.
Enter the server port number between 0 – 65535-1Uses a random port number for running the services.
Enter the service ID:fruit-serviceSets the service ID.
Select Reactive Framework:reactorChooses the Reactor framework for reactive data access.
Do you want to use Lombok?yesUtilizes the Lombok library to generate the entity class.
Select Annotation:MicronautDirects the CLI to use Micronaut annotations for code generation.
Enter the database name:fruitsSpecifies the database name.
Select Database Type:H2Selects H2 as the database management system.
Select Database Backend:JDBCChooses JDBC for database access.
Select Data Migration:liquibaseUses Liquibase as a data migration tool to create the database schema.
Select Messaging type:noneNo messaging type selected.
Do you want to add cache-caffeine support?yesEnables cache support using Caffeine.
Do you want to add Micrometer feature?yesCollects metrics on the endpoints and service calls.
Select Distributed Tracing:JaegerImplements Jaeger for distributed tracing.
Do you want to add GraphQL-Java-Tools support?yesAdds GraphQL support to the project.
Do you want to add GRPC support?noSkips GRPC support setup.
Do you want to use File Services?noThis article does not use storage services.
Do you want to configure VIEWS?yesConfirms adding a “view” dependency.
Select the views configuration:views-thymeleafAdds Thymeleaf as the template engine.

Entering Entity Attributes

Upon completing the configuration, you’ll be prompted to define the attributes of the entity. For the Fruit entity, enter the attributes as follows:

AttributeTypeValidationFindBy() MethodFindAllBy() MethodUpdateBy() Method
NameStringYesYesNo
quantityIntNoYesNo

Step 1 Output

At the conclusion of this step, MicrostarterCLI will generate various components including:

  • Entity classes
  • Service classes
  • Controller classes
  • Client classes
  • Test controllers
  • Liquibase XML files
  • Configurations

This output provides a structured foundation for further development of the FruitService microservice.

Step 2: Create the Vegetable Service

To create the Vegetable Service, which will manage the CRUD operations for Vegetable objects, follow the same steps as in Step 1:

  • Generate the Micronaut Application: Use Micronaut Launch or the init command with MicrostarterCLI to create the project.

mc init --name VegetableService --package io.hashimati

  • Navigate to the VegetableService Directory: After initializing the project, enter the VegetableService directory. Then, use the entity command to set up the service:

cd VegetableService

mc entity -e Vegetable

  • Answer Configuration Questions: Provide the following responses:
OptionAnswerDescription
Is the application monolithic?noSpecifies whether the service is monolithic or a microservice.
Enter the server port number between 0 – 65535-1Uses a random port number for running the services.
Enter the service ID:vegetable-serviceSets the service ID.
Select Reactive Framework:reactorChooses the Reactor framework for reactive data access.
Do you want to use Lombok?yesUtilizes the Lombok library to generate the entity class.
Select Annotation:MicronautDirects the CLI to use Micronaut annotations for code generation.
Enter the database name:vegetablesSpecifies the database name.
Select Database Type:H2Selects H2 as the database management system.
Select Database Backend:JDBCChooses JDBC for database access.
Select Data Migration:liquibaseUses Liquibase as a data migration tool to create the database schema.
Select Messaging type:noneNo messaging type selected.
Do you want to add cache-caffeine support?yesEnables cache support using Caffeine.
Do you want to add Micrometer feature?yesCollects metrics on the endpoints and service calls.
Select Distributed Tracing:JaegerImplements Jaeger for distributed tracing.
Do you want to add GraphQL-Java-Tools support?yesAdds GraphQL support to the project.
Do you want to add GRPC support?noSkips GRPC support setup.
Do you want to use File Services?noThis article does not use storage services.
Do you want to configure VIEWS?yesConfirms adding a “view” dependency.
Select the views configuration:views-thymeleafAdds Thymeleaf as the template engine.
  • Define Entity Attributes: Specify the attributes for the Vegetable entity as follows:
AttributeTypeValidationFindBy() MethodFindAllBy() MethodUpdateBy() Method
NameStringYesYesNo
quantityIntNoYesNo

Step 2 Output

At the end of this step, the MicrostarterCLI will generate the required components for the VegetableService, including entity classes, service classes, controllers, clients, test controllers, Liquibase XML files, and configurations, similar to the FruitService setup.

Step 3: Create the Eureka Server

In this step, we will set up the Eureka service discovery server, which will run on port 8761. Both the Fruit and Vegetable services will register with this server, as their Eureka clients will be configured to connect to localhost:8761.

To create the Eureka server project using MicrostarterCLI, execute the following command from the c:workspace directory:

mc eureka --version 2.7.8 --javaVersion 11

Configuring the Eureka Server

Once the command is executed, the MicrostarterCLI will generate the Eureka server project. Ensure that the following configurations are set in the application.yml or application.properties file of the generated Eureka server project:

  • Server Port: 8761
  • Eureka Instance Hostname: This should typically be set to localhost during local development.
  • Eureka Client Configuration: Ensure that the Eureka server does not register itself, as it’s the registry.

Example Configuration (application.yml)

server:

  port: 8761

eureka:

  instance:

    hostname: localhost

  client:

    registerWithEureka: false

    fetchRegistry: false

Running the Eureka Server

After setting up the configuration, start the Eureka server. The Fruit and Vegetable services will then be able to register themselves with this server, facilitating service discovery within the microservices architecture.

Step 4: Create the Gateway Service

In this final step, we will establish a Spring Cloud Gateway, which will act as a single entry point for all the microservices, including the Fruit and Vegetable services. The gateway will be configured to listen on port 8080.

To generate the Gateway project using MicrostarterCLI, execute the following command from the c:workspace directory:

mc gateway –version 2.7.8 –javaVersion 11

Configuring the Gateway Service

After generating the project, configure the Spring Cloud Gateway by editing the application.yml or application.properties file. Key configurations include setting up the gateway’s port and defining routes for the microservices.

Example Configuration (application.yml)

server:

  port: 8080

spring:

  cloud:

    gateway:

      routes:

      – id: fruit-service

        uri: http://localhost:8081

        predicates:

        – Path=/fruits/**

      – id: vegetable-service

        uri: http://localhost:8082

        predicates:

        – Path=/vegetables/**

In this configuration:

  • Gateway Port: The server will run on port 8080.
  • Routes: Define the routes for the Fruit and Vegetable services. For instance, requests to /fruits/** will be routed to the Fruit service, while requests to /vegetables/** will be routed to the Vegetable service. The URIs for the services should correspond to their respective ports set up during their creation.

Running the Gateway Service

After setting up the configuration, start the Gateway service. It will forward client requests to the appropriate microservices, acting as a central point of access and simplifying client interactions with the system.

Step 5: Configuring Gateway/Microservice Routes

In this step, we will set up the root routes for both the Fruit and Vegetable APIs through the Gateway. The MicrostarterCLI automatically generates these routes based on the @Controller annotations in the respective controller classes:

  • Fruit API Root Route: Defined in io.hashimati.controllers.FruitController, typically as /api/v1/fruit.
  • Vegetable API Root Route: Defined in io.hashimati.controllers.VegetableController, typically as /api/v1/vegetable.

To register these routes with the Gateway, use the register subcommand of the gateway command. Navigate to the c:workspacegateway directory and run the following command:

mc gateway register

Registering Routes

When prompted by the CLI, enter the necessary details for each service. You will need to run the register command twice—once for each service.

  1. For Fruit Service:
    • Service ID: fruit-service
    • Service Name: Fruit Service
    • Route: /api/v1/fruit
  2. For Vegetable Service:
    • Service ID: vegetable-service
    • Service Name: Vegetable Service
    • Route: /api/v1/vegetable

By completing these steps, you’ve configured the Gateway to direct CRUD operations to the respective services’ endpoints.

Running and Testing the Services

To run all the services, create a run.bat file with the following content:

cd c:workspaceeureka

start gradlew bootRun -x test&

cd c:workspaceFruitService

start gradlew run -x test&

cd c:workspaceVegetableService

start gradlew run -x test&

cd c:workspacegateway

start gradlew bootRun -x test&

Execute the run.bat file to start all the services. Once all services are running, open a web browser and navigate to the Eureka server’s URL. You should see all services listed as registered.

Testing the CRUD Endpoints

To test the CRUD operations, create a test.http file in IntelliJ with the following content:

POST http://localhost:8080/api/v1/fruit/save

Content-Type: application/json

{

    “name”: “Apple”,

    “quantity”: 100

}

###

GET http://localhost:8080/api/v1/fruit/findAll

###

POST http://localhost:8080/api/v1/vegetable/save

Content-Type: application/json

{

    “name”: “Onion”,

    “quantity”: 100

}

###

GET http://localhost:8080/api/v1/vegetable/findAll

Run these requests from IntelliJ to verify that the CRUD operations are working as expected through the Gateway.

Run CRUD Operations

To ensure that the CRUD operations are functioning correctly through the Gateway, follow these steps from IntelliJ:

  1. Create (POST): Send a request to the /create endpoint with the required data payload.
  2. Read (GET): Retrieve data using the /read endpoint.
  3. Update (PUT): Update existing data through the /update endpoint.
  4. Delete (DELETE): Remove data using the /delete endpoint.

For each operation, ensure you receive the expected status codes and responses. Detailed examples of these requests and their responses can be found in the project’s documentation.

Conclusion

In this tutorial, we’ve used MicrostarterCLI to set up a robust microservices architecture, featuring Eureka for service discovery, Spring Cloud Gateway for API routing, and CRUD services for entity management. We’ve also covered how to handle various aspects like JWT security, distributed tracing, messaging, and observability, with support for Groovy and Kotlin languages.

For more detailed information and advanced configurations, please visit the MicrostarterCLI project repository.

Happy coding!


Wanna become a data scientist within 3 months, and get a job? Then you need to check this out !