API Gateway Microservice Explanation
Spring Boot Application Configuration ( application.properties )
spring.application.name=api-gateway
server.port=9090
eureka.instance.client.serviceUrl.defaultZone =http://localhost:8761/
eureka/
## Routes for Employee Service
#spring.cloud.gateway.routes[0].id=employee
#spring.cloud.gateway.routes[0].uri=lb://employee
#spring.cloud.gateway.routes[0].predicates[0]=Path=/api/employee/**
## Routes for Department Service
#spring.cloud.gateway.routes[1].id=department
#spring.cloud.gateway.routes[1].uri=lb://department
#spring.cloud.gateway.routes[1].predicates[0]=Path=/api/department/**
## Automatic routing
spring.cloud.gateway.discovery.locator.enabled =true
#spring.cloud.gateway.discovery.locator.lower-case-service-id=true
spring.application.name: Sets the name of the Spring Boot application to "api-
gateway".
server.port: Specifies the port on which the application will run (9090).
eureka.instance.client.serviceUrl.defaultZone: Specifies the URL of the
Eureka server for service discovery.
spring.cloud.gateway.routes: Defines explicit routes for the Employee and
Department services. These routes are commented out in favor of automatic routing.
o id: Unique identifier for the route.
o uri: The URI of the service, using load balancing (lb://).
o predicates: Conditions under which the route is applied (e.g., path matching).
spring.cloud.gateway.discovery.locator.enabled: Enables automatic routing
based on services registered with Eureka.
spring.cloud.gateway.discovery.locator.lower-case-service-id: (Optional)
Configures whether service IDs should be lowercased in the routing configuration.
Main Application Class ( ApiGatewayApplication.java )
package com.example.api_gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import
org.springframework.cloud.client.discovery. EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
@SpringBootApplication: Annotates the main class to enable Spring Boot's auto-
configuration and component scanning.
@EnableDiscoveryClient: Enables service discovery integration with Eureka.
Summary
This code sets up a Spring Boot application to serve as an API Gateway in a microservice
architecture. It includes:
Configuration for the application name and port.
Integration with the Eureka server for service discovery.
Explicit route definitions for the Employee and Department services (commented
out).
Automatic routing enabled to dynamically route requests to services registered with
Eureka.
This setup allows the API Gateway to act as a single entry point for all microservices, routing
client requests to the appropriate services based on the URL paths. It simplifies client
interactions and provides a unified interface for accessing different microservices in the system.