DEV Community

Kishan Srivastava
Kishan Srivastava

Posted on

microservices

question
Model Microservice

This repo is intended as a starter project for anyone intending to write a new microservice. It demonstrates the following key features:
A basic gradle spring-cloud project
Integration with the service directory
Implementing a REST service with tests
Calling microservices in DWS fabric using webclient and feign.
After cloning you should, at the very least, change the following things before you import it into your IDE.
Change the package name from modelmicroservice to something more appropriate.
Edit settings.gradle and change the rootProject.name property name to your service name.
Edit src/main/resources/application.yaml and change spring.application.name to the name of your project. Review the other properties in this file.
Edit gradle.properties and review all the properties commented with TODO.
Generate a keystore for local testing. More info: Guide
This repo will never be finished. As we evolve our capability and update recommended versions this repo will change and evolve accordingly.
Auto-generated documentation

Swagger
Code Quality: SonarQube

Follow these steps to run a SonarQube instance locally to measure your code quality.
docker-compose -f src/main/docker/sonar.yml up
./gradlew sonar
Visit SonarQube Dashboard
Spring Boot 3

The model-microservice is now (Aug 2023) built against spring boot 3.

i need to understand properly what this repo is for
And what all technical knowledge should i have to use this and understand everything properly
what skills do i need to learn

gemini response
Of course. Based on the documentation you provided, here is an explanation of the "Model Microservice" repository and the skills needed to use it effectively.
What is this Repository For?
This repository serves as a starter project or template for developers who need to create a new microservice. Its primary purpose is to provide a standardized, pre-configured foundation that includes best practices and essential integrations, saving developers time and effort during the initial setup phase.
Instead of starting from an empty project, you can clone this repository and have a functional service skeleton that already demonstrates key capabilities:

Foundation: It's a project built with Gradle and the Spring Cloud framework, which are standard for building distributed systems.
Service Discovery: It includes integration with a "service directory," allowing your new service to register itself and discover other services within the network.
API Implementation: It provides a template for creating a RESTful API, complete with example tests, which is the standard way microservices communicate.
Inter-Service Communication: It shows how to call other microservices using two popular methods: WebClient (a modern, reactive web client) and Feign (a declarative web service client).
Modern Framework: The project is updated to use Spring Boot 3, ensuring it leverages the latest features and performance improvements.

In short, this repository is a blueprint that helps you bootstrap a new microservice quickly while adhering to established architectural patterns and tooling.
Technical Knowledge and Skills Required
To fully understand and effectively use this starter project, you should have a solid grasp of the following technologies and concepts. They are listed in order of importance, from foundational to specific.

  1. Foundational Skills These are the core competencies you'll need before you can work with the specifics of the repository.

Java Programming:

Description: The project is written in Java. You need strong proficiency in the language, including object-oriented principles, data structures, and core libraries. Familiarity with features from Java 17 or later is beneficial, as Spring Boot 3 requires it.
Why it's needed: To write the business logic, controllers, services, and repository layers of your microservice.

RESTful APIs:

Description: Understanding the principles of Representational State Transfer (REST). This includes concepts like resources, URIs, HTTP methods (GET, POST, PUT, DELETE), status codes, and data formats like JSON.
Why it's needed: Microservices primarily communicate via REST APIs. You will be building and consuming them.

Microservice Architecture:

Description: A conceptual understanding of why and how applications are broken down into smaller, independent services. This includes concepts like service discovery, configuration management, fault tolerance, and API gateways.
Why it's needed: This repository is a tool for implementing this architectural style. Knowing the "big picture" helps you understand the purpose of each feature (like service directory integration).

  1. Core Frameworks & Tools These are the specific technologies used directly in the repository.

Spring Framework / Spring Boot 3:

Description: This is the most critical framework. You should understand the core concepts of Spring, such as Dependency Injection (@Autowired), Inversion of Control (IoC), and aspect-oriented programming. For Spring Boot specifically, know how it simplifies configuration with auto-configuration, starters, and the application.yaml file.
Why it's needed: The entire application is built on Spring Boot. You'll use its annotations (@RestController, @Service, etc.) and configuration mechanisms daily.

Gradle:

Description: A build automation tool used to manage project dependencies, run tests, and build the application artifact. You should understand the structure of build.gradle and settings.gradle files and how to execute common tasks like gradlew build.
Why it's needed: You need to interact with Gradle to build the project, manage its libraries, and run tasks like the SonarQube analysis.

Spring Cloud:

Description: A sub-project of Spring that provides tools for building distributed systems. The repository mentions "service directory" integration, which is a core feature of Spring Cloud (often implemented with Netflix Eureka or Spring Cloud Consul).
Why it's needed: To make your service work correctly within a larger ecosystem of microservices.

  1. Specific Skills & Tooling These are skills for specific tasks mentioned in the repository's documentation.

Web Clients (WebClient and Feign):

Description: WebClient is a non-blocking, reactive client for making HTTP requests, part of the Spring WebFlux project. Feign is a declarative client that lets you define an API client by creating a simple Java interface.
Why it's needed: Your service will likely need to communicate with other services. The repository provides examples of both, and you should understand the trade-offs between them (e.g., reactive vs. blocking, verbosity vs. simplicity).

Docker and Docker Compose:

Description: Docker is a platform for creating, deploying, and running applications in containers. Docker Compose is a tool for defining and running multi-container Docker applications.
Why it's needed: The repository uses Docker Compose to run a local instance of SonarQube for code quality analysis. Basic knowledge of docker-compose up is required to follow the instructions.

API Documentation (Swagger/OpenAPI):

Description: Swagger (now known as the OpenAPI Specification) is a standard for documenting REST APIs. Tools like Springdoc-openapi can automatically generate this documentation from your code.
Why it's needed: To provide clear, interactive documentation for the API your service exposes, making it easy for other developers to understand and use.

Code Quality (SonarQube):

Description: A platform for continuous inspection of code quality to perform automatic reviews with static analysis of code to detect bugs, code smells, and security vulnerabilities.
Why it's needed: To ensure your code meets quality standards. You'll need to know how to run the analysis and interpret the results on the SonarQube dashboard.

question 2
explain with a simple example of a microservice that can be build with this starter template
how would it be different when this template was not present

gemini response
Of course. Let's walk through a simple, practical example of a microservice you could build with this template and then compare the development process with and without it.
Simple Example: A "Currency Exchange Rate" Microservice
Let's imagine you need to build a microservice called exchange-rate-service. Its sole purpose is to provide the current exchange rate between two currencies (e.g., USD to EUR).
What the Microservice Does:

Exposes a REST API Endpoint: It will have an endpoint like GET /api/v1/rates. You can query it with parameters, for example: GET /api/v1/rates?from=USD&to=EUR.
Returns a JSON Response: A successful request would return a simple JSON object:
json{
"fromCurrency": "USD",
"toCurrency": "EUR",
"rate": 0.95,
"timestamp": "2026-10-15T10:00:00Z"
}

Gets Data from Another Service: This exchange-rate-service doesn't calculate rates itself. It fetches them from a central, authoritative source, let's call it the market-data-provider service.
Registers Itself: It announces its presence on the network so other services (e.g., a trade-booking-service) can find and use it.

How You Would Build This Using the "Model Microservice" Template
Following the instructions in the repository, the process would be streamlined:

Clone and Rename:

You clone the model-microservice repository.
You perform the initial setup:

Change the package name from modelmicroservice to com.db.trading.exchangerate.
Edit settings.gradle to set rootProject.name = 'exchange-rate-service'.
Edit application.yaml to set spring.application.name: exchange-rate-service.

Result: You now have a working, buildable Spring Boot project correctly named and configured.

Define the API Endpoint:

You would create a new Java class, ExchangeRateController.java.
Using Spring's annotations (which are already in the project's dependencies), you define the endpoint. The template already has an example controller you can adapt.

java@RestController
@RequestMapping("/api/v1/rates")
public class ExchangeRateController {
// ... inject your service here

@GetMapping
public Rate getRate(@RequestParam String from, @RequestParam String to) {
    return exchangeRateService.getExchangeRate(from, to);
}
Enter fullscreen mode Exit fullscreen mode

}

Call the market-data-provider Service:

The template already includes WebClient and Feign as dependencies and provides examples of how to use them.
You could create a Feign client interface to declaratively define how to call the other service. The setup is already mostly done for you.

java@FeignClient(name = "market-data-provider")
public interface MarketDataProviderClient {
@GetMapping("/data/forex")
BigDecimal getRate(@RequestParam("pair") String currencyPair);
}

Your service logic would then simply call this Java interface, and Spring Cloud would handle the underlying HTTP request, service discovery, and response parsing.

Testing and Quality:

The template includes a testing framework (JUnit 5) and example tests for REST controllers. You can follow this pattern to write your own tests quickly.
To check your code quality, you just run the provided commands: docker-compose -f src/main/docker/sonar.yml up and ./gradlew sonar. The configuration is already done.

Run the Service:

You run the main application class. Because the template includes the Spring Cloud service discovery client, your service will automatically register itself with the service directory upon startup.

Key takeaway: The template provides the scaffolding. You don't spend time on setup, configuration, or figuring out which libraries to use. You focus almost immediately on writing the business logic for your specific service.

How It Would Be Different Without the Template (Starting from Scratch)
If this starter template did not exist, you would have to perform all of the following steps manually.

Project Initialization:

Go to a tool like start.spring.io or use your IDE's project wizard.
Manually select the project type (Gradle), language (Java), and Spring Boot version.
Dilemma: Which version of Spring Boot is standard? Is it compatible with the company's internal libraries? The template pre-answers this.
Manual Dependency Selection: You would need to manually add every single dependency:

Spring Web (for REST controllers)
Spring Boot Actuator (for health checks)
Spring Cloud Starter Netflix Eureka (or a similar client for service discovery)
Spring Cloud Starter OpenFeign (for the Feign client)
Spring Boot Starter Test (for testing)
Lombok (optional, for less boilerplate code)
Springdoc OpenAPI (for Swagger documentation)

Problem: You need to know exactly which dependencies are required and ensure their versions are compatible with each other. This is a common source of errors. The template provides a tested, known-good set of dependencies.

Configuration:

Create the application.yaml file from scratch.
Manually add configuration for the server port, application name, and the address of the service directory.
Manually configure logging patterns and levels.
The template provides a well-structured application.yaml with comments and placeholders for standard properties, which you would have to look up or guess.

Implementing Inter-Service Communication:

You would need to manually configure the Feign client or WebClient. This involves adding annotations like @EnableFeignClients to your main application class and potentially creating configuration beans for things like timeouts, retries, and error handling. The template would have this already set up.

Setting up Code Quality and Documentation:

SonarQube: You would need to find the correct SonarQube Docker image, write your own docker-compose.yml file, and configure the Gradle SonarQube plugin from scratch in your build.gradle file, connecting it to the Docker container.
Swagger: You would have to add the dependency and potentially write Java configuration beans to customize the generated API documentation (e.g., adding security definitions or metadata).

Build Logic:

You would write a build.gradle file from scratch. The template's gradle.properties and build.gradle files contain standardized version management, plugin configurations, and other best practices you would otherwise have to implement yourself.

In summary, without the template, a developer would spend a significant amount of time on boilerplate setup, configuration, and dependency management. This process is error-prone and leads to inconsistencies between microservices.
The template's value is that it encapsulates all of these initial decisions and configurations into a reusable, best-practice starting point, dramatically accelerating development and promoting standardization.

question 3
what things should i learn in proper sequence so that i completely understand each step of creation of a microservice with this template, so that i may understand the things used and also maybe later able to create a new microservice like this manually by my own

gemini response
Excellent question. Building a solid understanding requires a structured approach. Learning these concepts in the right order will ensure you grasp not just how to use the template, but why it is designed the way it is. This will empower you to use it effectively and eventually build a similar service from scratch.
Here is a recommended, sequential learning path, broken down into logical phases.

Phase 1: The Bedrock - Core Programming and Concepts
Start here. Without these fundamentals, the frameworks and tools in the later phases will be difficult to comprehend.

Java (Intermediate to Advanced):

What to Learn: Don't just learn the syntax. Focus on Object-Oriented Programming (OOP) principles (encapsulation, inheritance, polymorphism), interfaces, abstract classes, collections (Lists, Sets, Maps), and exception handling. Since Spring Boot 3 uses Java 17+, familiarize yourself with modern Java features like Records, var for local variables, and the Stream API for data manipulation.
Why: The entire application is written in Java. A deep understanding is non-negotiable for writing clean, efficient business logic.

HTTP and RESTful APIs:

What to Learn: Understand the client-server model of the web. Learn the core HTTP methods (GET, POST, PUT, DELETE), what they semantically represent, and the importance of HTTP status codes (e.g., 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error). Grasp the core principles of REST: resources, statelessness, and using JSON as a data format.
Why: This is the universal language of microservices. You will be designing, building, and consuming REST APIs.

Phase 2: The Engine - The Spring Framework
This is the most critical framework in the template. Master it, and you're halfway there.

Spring Core Concepts:

What to Learn: Focus on the two pillars of Spring: Inversion of Control (IoC) and Dependency Injection (DI). Understand what the Spring "Application Context" or "IoC Container" is. Learn the most common annotations: @Component, @Service, @Repository, and @Autowired.
Why: Spring manages the lifecycle of your objects (beans). Understanding DI is fundamental to how all the pieces of a Spring application are wired together.

Spring Boot:

What to Learn: Understand how Spring Boot simplifies Spring development. Focus on auto-configuration (how it automatically configures beans based on the JARs on your classpath), starter dependencies (e.g., spring-boot-starter-web), and externalized configuration using application.yaml or application.properties. Learn to build a simple REST controller using @RestController and @GetMapping/@PostMapping.
Why: The template is a Spring Boot project. This knowledge will allow you to understand how the service starts, how its configuration is managed, and how to add new API endpoints.

Gradle (Build Tool):

What to Learn: You don't need to be an expert, but you must understand the basics. Learn the purpose of build.gradle (declares dependencies and tasks) and settings.gradle (defines project structure). Know how to execute common tasks from the command line: ./gradlew build (compiles and packages the code), ./gradlew test (runs tests), and ./gradlew bootRun (runs the application).
Why: Gradle is the tool used to build, test, and manage all the libraries your project needs. You will interact with it constantly.

Phase 3: The Ecosystem - Connecting Microservices
Once you can build a standalone service, this phase teaches you how to make it part of a larger distributed system.

Microservice Architecture Concepts:

What to Learn: Before diving into the tools, understand the "why." Learn about key patterns like Service Discovery (how services find each other), Centralized Configuration (managing configuration for many services), and Fault Tolerance (e.g., circuit breakers).
Why: This provides the context for why tools like Spring Cloud are necessary.

Spring Cloud & Service Discovery:

What to Learn: Focus on the role of a "Service Directory" or "Discovery Server" (like Eureka, which is a common choice). Understand that when your service starts, it registers its name and address with this central server. When it needs to call another service, it asks the server for that service's address. Learn the annotations that enable this, like @EnableDiscoveryClient.
Why: In a microservice environment, you don't hardcode IP addresses. Service discovery allows services to find each other dynamically. The template is pre-configured for this.

Communicating Between Services (Feign & WebClient):

What to Learn:

Feign: Understand it as a "declarative" REST client. You create a Java interface, add annotations, and Spring Cloud automatically implements it for you. It's clean and easy to read.
WebClient: Learn this as the modern, more powerful way to make HTTP requests in Spring. It is non-blocking and reactive, which can be more efficient, but has a slightly steeper learning curve.

Why: Your microservice will inevitably need to call other microservices. The template provides examples of both, and you need to understand how to use them to fetch data.

Phase 4: The Polish - Professional Tooling & Practices
These tools ensure your microservice is maintainable, well-documented, and high-quality.

Testing in Spring:

What to Learn: Learn how to write unit tests for your services (@ExtendWith(MockitoExtension.class)) and integration tests for your REST controllers (@SpringBootTest with @AutoConfigureMockMvc or WebTestClient). Understand the difference between mocking dependencies and running a test with a full application context.
Why: The template includes a testing setup. Writing automated tests is crucial for ensuring your service works correctly and doesn't break when you make changes.

API Documentation (Swagger/OpenAPI):

What to Learn: Understand that tools like Springdoc-openapi scan your @RestController code to automatically generate interactive API documentation (a Swagger UI page). Learn how to add annotations (@Operation, @ApiResponse) to make this documentation more descriptive.
Why: Good documentation makes your service easy to use for other developers and teams. The template automates the setup.

Docker & Docker Compose:

What to Learn: Understand what a Docker container is (a lightweight, portable package of an application and its dependencies). Learn the basics of Docker Compose for running multi-container applications from a single docker-compose.yml file. You only need to know how to run docker-compose up to start.
Why: The template uses this to run external dependencies locally, like the SonarQube database and server. This avoids complex local installations.

Code Quality (SonarQube):

What to Learn: Understand that SonarQube is a static analysis tool that scans your code for bugs, vulnerabilities, and "code smells" (bad practices). Learn how to run the Gradle task (./gradlew sonar) and how to interpret the dashboard to identify areas for improvement in your code.
Why: This helps you maintain high code quality and write more secure, robust applications.

By following this path, you will progressively build the knowledge required to not only use the template, but to understand its value and replicate its functionality on your own.

Top comments (0)