Spring Cloud API Gateway
Introduction
API Gateway is the single entry point for all microservices. It receives client requests, routes them to the appropriate service, and returns the response. It acts as the primary contact for all incoming client requests.
| Function | Description |
|---|---|
| Routing | Sends requests to the correct microservice |
| Load Balancing | Distributes traffic across service instances |
| Security | Authentication, Authorization, JWT |
| Rate Limiting | Controls number of requests (prevents overload) |
| Logging & Monitoring | Tracks requests and responses |
| Transformation | Modify request/response (headers, body, URL) |
API Gateway Implementation
1. Add Gateway Starter Dependency
Add the Spring Cloud Gateway (Reactive) dependency in pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
2. Configure Routing for Microservices
Routing can be configured in two ways:
- Programmatic : Define routes using a
@Bean -
Properties / Declarative : Define routes in
application.propertiesorapplication.yml2.1 Routing Using application.properties
Example route for User Microservice
Example
API Gateway Configuration
User Service Endpoint : http://localhost:8081/user/create Call the user-service API via the gateway as : http://localhost:8080/user/create
| Request via Gateway | Routes to backend service URL |
|---|---|
| http://localhost:8080/user/create | http://localhost:8081/user/create |
Then,
1. Flow
- The gateway will receive this request at
/user/create, match thepredicate /user/** - proxy route it to the user-service running at http://localhost:8081/user/create.
- Gateway routes predicate's
Path=/user/**decides which URLs get forwarded.
2. Gateway Logging
When a request hits the API Gateway, logs like:
This means:- Request
/user/readcame to gateway - Gateway forwarded it to
User Service - Response returned successfully