Microservice

Microservice

INTRODUCTION

A Microservice is a small, independent, and self-contained application designed to perform a single, specific business function.

Each Microservice runs in its own process and communicates with other microservices through lightweight protocols, usually HTTP REST APIs or message queues like RabbitMQ or Kafka.

Instead of building one large monolithic system, microservices break the system into smaller components.

Each component focuses on a single function, such as user authentication, sending email.

Difference between Monolithic and microservice

  • In a monolithic weather app, everything (city info, weather info, user info) exists in one large codebase.
  • In a microservice architecture, each of those responsibilities becomes a separate service.

Frameworks like Spring Boot simplify the complexities in microservice.

Spring Boot Overview

Spring Boot is a Java framework that allows developers to build production-ready applications quickly with minimal configuration.

In a microservice setup, each Spring Boot app is an independent service with:

  • Its own configuration
  • Its own REST endpoints
  • Its own (optional) database

These microservices communicate with each other using:

  • HTTP REST APIs
  • Or message queues (like RabbitMQ or Kafka)

Sample: Building a Weather Microservice

Let’s build a Weather Service using Spring Boot that fetches temperature data based on latitude and longitude.

Step 1: Create a New Spring Boot Project

In IntelliJ IDEA:

  1. Click File → New Project
  2. Choose Spring Boot
  3. Provide project details like:
  • Project name: weather
  • Group: com.maegham
  • Artifact: weather
  1. Click Create

Step 2: Add Spring Boot Web Dependency

In your pom.xml, include the Spring Web dependency to create REST APIs.


<dependencies>

  <!-- Spring Web dependency for building REST APIs -->

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

    <version>3.5.7</version>

  </dependency>

  <!-- Lombok for auto-generating getters/setters -->

  <dependency>

    <groupId>org.projectlombok</groupId>

    <artifactId>lombok</artifactId>

    <version>1.18.30</version>

    <scope>provided</scope>

  </dependency>

  <!-- Swagger/OpenAPI for API documentation -->

  <dependency>

    <groupId>org.springdoc</groupId>

    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>

    <version>2.6.0</version>

  </dependency>

  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-validation</artifactId>

    <version>3.5.7</version>

  </dependency>

</dependencies>


Explanation:

  • spring-boot-starter-web → Everything needed to build web applications (Spring MVC, Tomcat).
  • lombok → Generates boilerplate code like getters/setters.
  • springdoc-openapi → Enables API documentation with Swagger UI.
  • spring-boot-starter-validation → Adds request validation capabilities.

Project Architecture

weather/

 ├── config/

 │  └── RestTemplateConfig.java

 ├── controller/

 │  └── WeatherController.java

 ├── model/

 │  └── WeatherRequest.java

 ├── service/

 │  └── WeatherService.java

 └── WeatherApplication.java

This structure follows a clean, layered architecture:

Layer

Responsibility

Controller

Handles API requests and responses

Service

Contains the core business logic

Model

Defines input/output data

Config

Provides reusable beans like Rest Template


Step 3: Create the Main Application Class


@SpringBootApplication

public class WeatherApplication {

  public static void main(String[] args) {

    SpringApplication.run(WeatherApplication.class, args);

  }

}


Explanation:

This is the main class the starting point of your Spring Boot app.

When you run it, Spring Boot:

  • Initializes the entire application context
  • Scans all packages for components like @RestController, @Service, etc.
  • Starts an embedded Tomcat server on port 8080

Annotations

Annotations in Spring Boot is to use in-code instructions to automate configuration and reduce code setup.

  • @SpringBootApplication = combination of:
  • @Configuration – defines beans
  • @EnableAutoConfiguration – configures dependencies automatically
  • @ComponentScan – detects Spring components

Step 4: Create RestTemplate Configuration


@Configuration

public class RestTemplateConfig {

  @Bean

  public RestTemplate restTemplate(){

    return new RestTemplate();

  }

}



Explanation:

This class provides a RestTemplate bean — a Spring helper used to make HTTP requests to external APIs.

  • @Configuration → Marks this class as a source of bean definitions
  • @Bean → Registers RestTemplate for dependency injection (@Autowired)

Now, any class can call external APIs using RestTemplate without manually creating HTTP clients.

Step 5: Create a Request Model (POJO)

@Data

public class WeatherRequest {

  private Double latitude;

  private Double longitude;

}



Explanation:

This defines the structure of data expected in a POST request.

  • @Data → Lombok annotation that auto-generates getters, setters, and utility methods.
  • Fields represent latitude and longitude for weather lookup.

Example Request:

{

  "latitude": 37.7749,

  "longitude": -122.4194

}

Step 6: Create the Service Layer


@Service

@AllArgsConstructor

public class WeatherService {

  @Autowired

  private final RestTemplate restTemplate;

  public String getWeather(double latitude, double longitude) {

    String url = String.format("https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s&hourly=temperature_2m",

        latitude, longitude);

    return restTemplate.getForObject(url, String.class);

  }


}



Explanation:

The service layer contains the core logic of the application.

  • @Service → Marks this class as a business logic layer
  • RestTemplate → Makes HTTP GET calls to external APIs.
  • getWeather() → Builds a dynamic URL using coordinates and returns the response from Open-Meteo.


Step 7: Create the REST Controller

@RestController

@RequestMapping("/api/weather")

public class WeatherController {


  @Autowired

  public WeatherService weatherService;


  @GetMapping

  public ResponseEntity<String> getWeather(@RequestParam double latitude,

                      @RequestParam double longitude) {

    String data = weatherService.getWeather(latitude, longitude);

    return ResponseEntity.ok(data);

  }


  @PostMapping

  public ResponseEntity<String> getWeatherPost(@RequestBody WeatherRequest request) {

    String data = weatherService.getWeather(request.getLatitude(), request.getLongitude());

    return ResponseEntity.ok(data);

  }


}



Explanation:

The controller defines your REST API endpoints.

  • @RestController → Indicates that this class handles RESTful requests.
  • @RequestMapping("/api/weather") → Base URL for all endpoints.
  • @GetMapping → Handles GET requests with query params.
  • @PostMapping → Handles POST requests with JSON body.

Both endpoints call the same service method to fetch live weather data.

How Everything Connects

Start the application

MS_4.png

  1. WeatherApplication.java will starts the Spring Boot app.
  2. The embedded Tomcat server runs on the default port 8080.
  3. User sends a GET or POST request to “/api/weather”.
  4. The Controller parse the input and invoke WeatherService.
  5. WeatherService communicate with the Open-Meteo API using RestTemplate.
  6. The response returned to client in JSON.




Request

Response

This represents hourly temperature data for the specified location.

Structure

This layered structure ensures your code is:

  • Easy to test
  • Easy to maintain
  • Easy to extend (e.g., add caching, error handling)

Key Spring Annotations

Annotation

Description

@SpringBootApplication

Marks the main entry point and enables auto-configuration

@Data

Generates getters/setters using Lombok

@Service

Defines a service layer component

@RestController

Creates RESTful web services

@RequestMapping

Defines a base path for endpoints

@Autowired

Injects dependencies automatically

@GetMapping

Maps HTTP GET requests

@PostMapping

Maps HTTP POST requests


Conclusion

This project demonstrates:

  • The structure of a microservice project
  • To make external API calls
  • To handle both GET and POST requests


ibm sterling oms configuration Microservice