Create an API Gateway with Load Balancer Using Java
Nowadays every application is moving to microservice architecture. In this architecture, API Gateway has an important role. Let's build a simple API gateway using Java.
Join the DZone community and get the full member experience.
Join For FreeUsed Libraries
- Netflix Eureka naming server
- Netflix Zuul
- Ribbon
- Feign
This Architecture Contains Four Applications
- Load balancing application [netflix-eureka-naming-server]
- API gateway application [api-gateway-server]
- Server application [micro-service-server]
- Client application [micro-service-client]
Steps To Run The Applications
- Install JDK 11 or latest.
- Clone git repository of the project into local.
- Github: https://github.com/VishnuViswam/LOAD-BALANCER-WITH-API-GATEWAY.git
- Run Load balancing application first.
- Run The API gateway application.
- Then run Server application in two ports.
- At last run Client application.
1) Load Balancing Application
All client server communication will be done through this load balancing server application.
pom.xml
We are using netflix-eureka-server
library to enable the communication between client and server.
xxxxxxxxxx
<properties>
<java.version>11</java.version>
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
application.properties
xxxxxxxxxx
spring.application.name=netflix-eureka-naming-server // application unique name
server.port=8761 // It will be the default port which eureka naming server
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
NetflixEurekaNamingServerApplication.java
@EnableEurekaServer
named annotation will allow the eureka server to control this application.
xxxxxxxxxx
// to enable the communication with Eureka server
public class NetflixEurekaNamingServerApplication {
public static void main(String[] args) {
SpringApplication.run(NetflixEurekaNamingServerApplication.class, args);
}
}
After running this application we can access the eureka server dashboard under following URL.
Link: http://localhost:8761
Eureka Server Dashboard
2) API Gateway Application
This application will act as a middleware in between Server Application and Client Application.
All requests going to the Server application will be filtered here.
We are using spring-cloud-starter-netflix-zuul
library to enable this filtering process.
netflix-eureka-client
is the library which used to register the application with Eureka naming server.
Zuul Dependency
xxxxxxxxxx
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
pom.xml
xxxxxxxxxx
<properties>
<java.version>11</java.version>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</dependencies>
application.properties
xxxxxxxxxx
spring.application.name=api-gateway-server // application unique name
server.port=8765 // application will be running under this port
eureka.client.service-url.default-zone=http://localhost:8761/eureka // end point of load balancing server
ApiGatewayApplication.java
@EnableDiscoveryClient
named annotation used to register the application with Eureka server in the main class.
@EnableZuulProxy
named annotation used to connect the Zuul library.
xxxxxxxxxx
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
ZuulLoginFilter.java
- It is the class where all the APIs getting flittered.
- We extended one class named by "ZuulFilter".
- Four methods will be override from this class.
filterType():
- The interruption time of a request will be decided in this method.
- pre key is used to filter before reaching the Server application .
- post key is used to filter when response came back from the Server application.
- error key is used to filter any error happened.
filterOrder():
- To set the priority of the filter process.
shouldFilter():
- To decide whether the request is filter or not.
run():
- This method will trigger after filtering process. So that we can write the business logic what ever we required.
xxxxxxxxxx
"/client") (
public class ZuulLoginFilter extends ZuulFilter {
public String filterType() {
return "pre"; // filter before request is executed
// return "post"; filter after request is executed
//return "error"; upon request error
}
public int filterOrder() {
return 1;
}
public boolean shouldFilter() {
return true;
}
public Object run() throws ZuulException {
logger.info("Request is filtered");
HttpServletRequest httpServletRequest = RequestContext.getCurrentContext().getRequest();
logger.info("request -> {} request uri -> {} ",
httpServletRequest, httpServletRequest.getRequestURI());
return null;
}
}
After running this application, the instance of this application will be appear in the Eureka server dashboard.
3) Server Application
In order to perform load distribution this application need to run in two instances.
spring-cloud-starter-netflix-eureka-client
library used to enable communication with Eureka naming server
xxxxxxxxxx
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
pom.xml
xxxxxxxxxx
<properties>
<java.version>11</java.version>
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
application.properties
xxxxxxxxxx
spring.application.name=micro-service-server // application unique name
server.port=4000 // application will be running under this port
eureka.client.service-url.default-zone=http://localhost:8761/eureka // end point of load balancing server
MicroServiceServerApplication.java
@EnableDiscoveryClient
named annotation to register the application with eureka server.
xxxxxxxxxx
public class MicroServiceServerApplication {
public static void main(String[] args) {
SpringApplication.run(MicroServiceServerApplication.class, args);
}
}
- Run Server application instance in two ports
- First simply run the application as java application using main method.
To run one more instance in another port we need to edit the <b>Run/Debug Configurations</b> In the IDE.
In IntelliJ:
Click on the Edit Configuration option, it will be available on the right top side of the menu bar.
It will open a window as follows. Then enable Allow parallel run and press apply.
Now change the port in the property file as 4001. Then run once again.
In Eclipse:
Right-click on the main class -> click properties -> select main class -> click new button and add -Dserver. port=4001 in the Vm Arguments as shown in the following images.
Then select the new configuration and run. Now these two instances of server will be appear in the eureka server dashboard.
4) Client Application
- This application will perform as consumer of APIs which is written in the main server.
- It consumes the APIs from the both main server instance based on availability through load balancer.
- We also use
netflix-eureka-client
library to communicate with load balancer application.
OpenFeign
- We are using OpenFeign to consume APIs rather than using traditional HTTP libraries.
- OpenFeign will act as a proxy in between server and client.
xxxxxxxxxx
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Eureka Client & Ribbon
- Ribbon will do the automatic switching of servers in the client-side
- Eureka will help us to dynamically add main server instances to the load balancer according to traffic.
xxxxxxxxxx
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
pom.xml
xxxxxxxxxx
<properties>
<java.version>11</java.version>
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
application.properties
xxxxxxxxxx
server.servlet.contextPath=/microservice
spring.application.name=micro-service-client // application unique name
server.port=5000 // application will be running under this port
eureka.client.service-url.default-zone=http://localhost:8761/eureka // end point of load balancing server
MicroServiceClientApplication.java
@EnableDiscoveryClient
named annotation used to register the application with eureka server in the main class.@EnableFeignClients
named annotation used to connect the feign library.
xxxxxxxxxx
"com.microservices.client") (
public class MicroServiceClientApplication {
public static void main(String[] args) {
SpringApplication.run(MicroServiceClientApplication.class, args);
}
}
ClientController.java
- It is an ordinary REST controller class
xxxxxxxxxx
"/client") (
public class ClientController {
private ApiProxy apiProxy;
"/technologyInfo/{platform}") (
public ResponseModel getTechnologyInfo( ("platform") String platform) {
// API calling using proxy interface and mapping into ResponseModel named Object.
ResponseModel responseModel = apiProxy.retrieveTechnologyInfo(platform);
return responseModel;
}
}
ApiProxy.java
- Act as proxy class in between API and client.
@FeignClient(name = "api-gateway-server")
annotation will enable the communication from the Client application to API gateway application.@RibbonClient(name = "micro-service-server")
annotation will tell the API gateway application to where the request has to go.micro-service-server
should be the name of Server application.
xxxxxxxxxx
name = "api-gateway-server") (
name = "micro-service-server") (
public interface ApiProxy {
"micro-service-server/server/technologyInfo/{platform}") (
ResponseModel retrieveTechnologyInfo( ("platform") String platform);
}
ResponseModel.java
- It is a traditional model class.
xxxxxxxxxx
public class ResponseModel {
private String tittle;
private String platform;
private String usedFor;
private Short serverPort;
--------
---
}
After running the client application, an instance of this application also appears in the Eureka server dashboard.
Result
Now we can see four application instances are running in Eureka server dashboard.
Call client application API.
URI: http://localhost:5000/microservice/client/technologyInfo/java
Response:
xxxxxxxxxx
{"tittle":"Technology Stack","platform":"Java","usedFor":"Secured Web Services","serverPort":4000}
Do Refresh:
xxxxxxxxxx
{"tittle":"Technology Stack","platform":"Java","usedFor":"Secured Web Services","serverPort":4001}
- From the result we can understand that the API response is receiving from different servers by identifying port change. That means the requests are distributing in between two Server applications.
- And in the console of API gateway application we can see the message Request is filtered. That means API request also has been filtered by our application.
Opinions expressed by DZone contributors are their own.
Comments