Microservices with Spring Cloud

🌿 Spring BootLesson 14Advanced

Spring Cloud extends Spring Boot with tools for distributed systems: service discovery (Eureka), client-side load balancing (Spring Cloud LoadBalancer), API gateway (Spring Cloud Gateway), and external configuration (Config Server).

1 Service Discovery with Eureka
Java — Eureka Server & Client
// --- EUREKA SERVER ---
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServer { public static void main(String[] args) { SpringApplication.run(DiscoveryServer.class, args); } }

# application.yml (Eureka Server)
server.port: 8761
eureka.client.register-with-eureka: false
eureka.client.fetch-registry: false

// --- MICROSERVICE CLIENT ---
@SpringBootApplication
@EnableDiscoveryClient
public class UserService { ... }

# application.yml (Client)
spring.application.name: user-service
eureka.client.service-url.default-zone: http://localhost:8761/eureka/
2 Inter-Service Communication with OpenFeign
Java — Feign Client
// Declarative HTTP client — no RestTemplate boilerplate
@FeignClient(name = "product-service")  // Name matches spring.application.name
public interface ProductClient {

    @GetMapping("/api/v1/products/{id}")
    ProductDto getProduct(@PathVariable Long id);

    @GetMapping("/api/v1/products")
    Page<ProductDto> getProducts(@RequestParam String category,
                                  @RequestParam int page);
}

// Use in your service — Feign handles HTTP, load balancing, retries
@Service
@RequiredArgsConstructor
public class OrderService {
    private final ProductClient productClient;

    public Order createOrder(CreateOrderRequest req) {
        ProductDto product = productClient.getProduct(req.getProductId());
        // Build order using product data...
    }
}

// Enable Feign in main app:
@SpringBootApplication
@EnableFeignClients
public class OrderServiceApp { ... }
3 Code Challenge
Challenge: Build a mini microservices system with three services: user-service, product-service, and order-service. The order-service should use Feign to call both user-service and product-service. Register all three with Eureka and route external traffic through a Spring Cloud Gateway.