Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Microservice Architecture in Java | Why we should use Spring Boot to implement Microservices Architecture

 What is Microservices?

Microservices Architecture is a software development approach where a large application is built as a collection of small, independent services.



Each service:

✅ Runs independently

✅ Has its own database

✅ Can be deployed separately

✅ Communicates via APIs (HTTP/REST)

🎯 What We Are Building

We will create 4 projects:

  1. Eureka Server

  2. API Gateway

  3. Customer Service

  4. Order Service

When to Use Microservices?

Use Microservices when:

  • Application is large and complex

  • Multiple teams are working

  • High scalability required

  • Continuous deployment needed

Avoid Microservices for:

  • Small projects

  • Simple applications

  • Beginner-level applications

🚀 Why Spring Boot Uses Microservices?

Spring Boot is widely used to build microservices because it makes creating independent, production-ready services very easy.

✅ Reasons Spring Boot is Perfect for Microservices

  1. Standalone Applications

    • Each microservice runs independently (embedded Tomcat/Jetty).

    • No need for external server setup.

  2. Auto Configuration

    • Minimal configuration required.

    • Faster development.

  3. Easy REST API Creation

    • Simple @RestController support.

    • JSON support built-in.

  4. Spring Cloud Integration

    • Works seamlessly with:

      • Service Discovery

      • API Gateway

      • Load Balancing

      • Circuit Breaker

  5. Microservice Friendly Features

    • External configuration

    • Actuator monitoring

    • Easy Docker & Kubernetes deployment


🔍 What is Service Discovery?

In microservices, services run on different ports or machines.

Example:

  • Customer Service → Port 8081

  • Order Service → Port 8082

If Order Service wants to call Customer Service, how does it know:

  • IP address?

  • Port number?

  • If service is running?

👉 This problem is solved by Service Discovery.


📌 Definition

Service Discovery is a mechanism where services:

  1. Register themselves

  2. Discover other services dynamically

Instead of calling:

http://localhost:8081/customers

We call:

http://CUSTOMER-SERVICE/customers

The discovery server resolves it automatically.


🏗 Example: Eureka

Netflix Eureka is commonly used with Spring Boot.

How It Works:

  1. All services register with Eureka.

  2. Eureka keeps service list.

  3. Other services ask Eureka for service location.

  4. Load balancing happens automatically.

Flow:

Customer Service → Register → Eureka
Order Service → Ask Eureka → Get Customer Service URL

🌐 What is Spring Cloud Gateway?

Spring Cloud Gateway is an API Gateway built for microservices.

It acts as a single entry point for all client requests.


🎯 Why We Need API Gateway?

Without Gateway:

Client → Customer Service (8081)
Client → Order Service (8082)
Client → Payment Service (8083)

Client must know all ports ❌

With Gateway:

Client → API Gateway (8080) → Routes to services

Client calls only ONE URL ✅


🔧 What Gateway Does

  1. Routes requests

  2. Load balancing

  3. Authentication & Authorization

  4. Logging

  5. Rate limiting

  6. Security filtering


🏗 Example Routing Configuration

spring:
cloud:
gateway:
routes:
- id: customer-service
uri: lb://CUSTOMER-SERVICE
predicates:
- Path=/customers/**

Here:

  • lb:// → Load Balanced

  • Gateway uses Service Discovery

  • Automatically finds service from Eureka


🏛 Complete Microservices Flow

Client

Spring Cloud Gateway

Service Discovery (Eureka)

Customer / Order / Payment Services

🧱 STEP 1 — Create Eureka Server

✅ 1. Create Spring Boot Project

Go to Spring Initializr:

  • Project: Maven

  • Dependencies:

    • Spring Web

    • Eureka Server


✅ 2. Add Annotation

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}

✅ 3. application.yml

server:
port: 8761

eureka:
client:
register-with-eureka: false
fetch-registry: false

▶ Run Project

Open browser:

http://localhost:8761

Eureka Dashboard should open ✅


🧱 STEP 2 — Create Customer Service

✅ 1. Create Spring Boot Project

Dependencies:

  • Spring Web

  • Spring Data JPA

  • H2 Database

  • Eureka Client


✅ 2. application.yml

server:
port: 8081

spring:
application:
name: CUSTOMER-SERVICE
h2:
console:
enabled: true

eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka

✅ 3. Entity

@Entity
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;

// getters and setters
}

✅ 4. Repository

public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

✅ 5. Controller

@RestController
@RequestMapping("/customers")
public class CustomerController {

@Autowired
private CustomerRepository repository;

@PostMapping
public Customer save(@RequestBody Customer customer) {
return repository.save(customer);
}

@GetMapping
public List<Customer> getAll() {
return repository.findAll();
}
}

▶ Run Customer Service

Check Eureka dashboard → CUSTOMER-SERVICE should appear ✅


🧱 STEP 3 — Create Order Service

✅ 1. Create Spring Boot Project

Dependencies:

  • Spring Web

  • Spring Data JPA

  • H2

  • Eureka Client


✅ 2. application.yml

server:
port: 8082

spring:
application:
name: ORDER-SERVICE

eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka

✅ 3. Entity

@Entity
public class Orders {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productName;
private int quantity;
}

✅ 4. Repository

public interface OrderRepository extends JpaRepository<Orders, Long> {
}

✅ 5. Controller

@RestController
@RequestMapping("/orders")
public class OrderController {

@Autowired
private OrderRepository repository;

@PostMapping
public Orders save(@RequestBody Orders order) {
return repository.save(order);
}

@GetMapping
public List<Orders> getAll() {
return repository.findAll();
}
}

▶ Run Order Service

Check Eureka → ORDER-SERVICE appears ✅


🧱 STEP 4 — Create API Gateway

✅ 1. Create Spring Boot Project

Dependencies:

  • Spring Cloud Gateway

  • Eureka Client


✅ 2. application.yml

server:
port: 8080

spring:
application:
name: API-GATEWAY

cloud:
gateway:
routes:
- id: customer-service
uri: lb://CUSTOMER-SERVICE
predicates:
- Path=/customers/**

- id: order-service
uri: lb://ORDER-SERVICE
predicates:
- Path=/orders/**

eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka

▶ Run Gateway


🚀 Final Run Order

Start in this order:

  1. Eureka Server (8761)

  2. Customer Service (8081)

  3. Order Service (8082)

  4. API Gateway (8080)


🧪 Test Using Gateway

Instead of calling 8081 or 8082 directly, use:

Create Customer

POST http://localhost:8080/customers

Get Customers

GET http://localhost:8080/customers

Create Order

POST http://localhost:8080/orders

Post a Comment

0 Comments