🏗️ Microservices & Spring Cloud
Build distributed, scalable, resilient microservice architectures using Spring Boot, Spring Cloud, Eureka, API Gateway, and Resilience4j.
What is Microservices Architecture?
Microservices Architecture is an architectural style that structures an application as a collection of small, autonomous, loosely coupled services. Each service is centered around a specific business domain, runs in its own process, and communicates with other services using lightweight protocols (HTTP/REST or async messaging queues like Kafka).
| Dimension | Monolithic Architecture | Microservices Architecture |
|---|---|---|
| Deployment | Single deployment unit (WAR/JAR) | Independently deployable micro-services |
| Scaling | Scale the entire application monolithic instance | Scale specific high-demand services independently |
| Tech Stack | Unified single technology stack | Polyglot (different tech per microservice) |
| Fault Isolation | Bug in one module can crash whole app | Service failure isolated via Circuit Breakers |
Core Spring Cloud Components
Spring Cloud provides tools for developers to quickly build common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing).
- Spring Cloud Netflix Eureka: Service Registration and Discovery server.
- Spring Cloud Gateway: Intelligent API Gateway for routing, security, and rate limiting.
- OpenFeign: Declarative REST client for inter-service communication.
- Resilience4j: Fault tolerance library implementing Circuit Breaker, Rate Limiter, & Retry patterns.
- Spring Cloud Config: Centralized external configuration server backed by Git.
1. Eureka Service Discovery
Instead of hardcoding hostnames and ports, microservices register themselves with a Eureka Naming Server. Microservices query Eureka to dynamically discover target service locations.
package com.example.serviceregistry; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
2. Inter-Service Communication with OpenFeign
Spring Cloud OpenFeign allows you to write declarative REST clients by defining annotated Java interfaces instead of manually executing `RestTemplate` or `WebClient` boilerplate.
package com.example.orderservice.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(name = "PAYMENT-SERVICE") public interface PaymentClient { @GetMapping("/api/payments/status/{orderId}") String getPaymentStatus(@PathVariable("orderId") String orderId); }
3. Spring Cloud API Gateway
The API Gateway acts as the single entry point for all client requests, handling routing, cross-cutting security (JWT validation), rate limiting, and CORS headers.
spring:
cloud:
gateway:
routes:
- id: order-service
uri: lb://ORDER-SERVICE
predicates:
- Path=/api/orders/**
- id: payment-service
uri: lb://PAYMENT-SERVICE
predicates:
- Path=/api/payments/**
4. Circuit Breaker with Resilience4j
The Circuit Breaker pattern prevents cascading failures across microservices when a downstream dependency experiences slowness or outages.
@Service public class OrderService { @Autowired private PaymentClient paymentClient; @CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback") public String processOrder(String orderId) { return paymentClient.getPaymentStatus(orderId); } // Fallback executes when downstream payment service is DOWN public String paymentFallback(String orderId, Exception ex) { return "Payment service currently unavailable. Order queued."; } }