Implementing API Gateway | SpringBoot Microservices
We have 3 microservices for our Hotel Rating Application →
UserService - localhost:8081/users
HotelService - localhost:8082/hotels
RatingService - localhost:8083/ratings
Above 3 microservices are already registered as Discovery Client on our Discover server.
Here we will try to implement API Gateway for our Hotel Rating Application -
Step 1 → Add dependencies.
Cloud Bootstrap | SPRING CLOUD
Gateway | SPRING CLOUD ROUTING
Spring Reactive Web | WEB (Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or when built as a WAR.)
Eureka Discovery Client | SPRING CLOUD DISCOVERY
Step 2 → Register our API Gateway application as Discovery Client on our Discovery Server. For this we already have added dependencies in step 1 (“Cloud Bootstrap | SPRING CLOUD” and “Eureka Discovery Client | SPRING CLOUD DISCOVERY“). We just need to add the configurations, for which you refer the article -
Implementing Service Discovery Client in SpringBoot | Microservices
spring:
application:
name: ApiGateway
server:
port: 8091
eureka:
instance:
prefer-ip-address: true
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
(NOTE : Make sure your Discovery Server microservice is running on default port: 8761 (localhost:8761) otherwise the app won’t work maybe because it requires extra configurations.)
Step 3 → Configuring routes (Check “Spring Cloud Gateway” documentation for latest updates).
spring:
cloud:
gateway:
routes:
- id: USERSERVICE
uri: lb://USERSERVICE
predicates:
- Path=/users/**
- id: HOTELSERVICE
uri: lb://HOTELSERVICE
predicates:
- Path=/hotels/**
- id: RATINGSERVICE
uri: lb://RATINGSERVICE
predicates:
- Path=/ratings/**
Now we can access these microservices endpoints as →
UserService - localhost:8081/users → localhost:8091/users
HotelService - localhost:8082/hotels → localhost:8091/hotels
RatingService - localhost:8083/ratings → localhost:8091/ratings
So we can see that now we have a single point of entry for all our microservices which is our API Gateway microservice.
Please refer to “Spring Cloud Gateway” documentation for latest updates.