{{announcement.body}}
{{announcement.title}}

Create a Load Balancer Using Java

DZone 's Guide to

Create a Load Balancer Using Java

Load balancing server [netflix-eureka-naming-server], Server application [micro-service-server], and Client application [micro-service-client].

· Java Zone ·
Free Resource

This Architecture Contains Three Applications

  • Load balancing server [netflix-eureka-naming-server]
  • Server application [micro-service-server]
  • Client application [micro-service-client]

Network Architecture of the System

Eureka naming server

Steps to Run Applications

  • Install JDK 11 or the latest.
  • Clone git repository of the project into local.
  • Github: https://github.com/VishnuViswam/LOAD-BALANCER
  • Run Netflix-eureka-naming-server application first.
  • Then run a microservice-server application in two ports.
  • At last run micro-service-client.

Working and Configurations

1) Load Balancing Server

All client-server communication will be done through this load balancing server.

pom.xml

  • We are using Netflix-eureka-server library to enable the communication between client and server.
XML
 




xxxxxxxxxx
1
13


 
1
<properties>
2
    <java.version>11</java.version>  
3
    <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
4
</properties> 
5
<dependencies>
6
  <dependency>    
7
    <groupId>org.springframework.cloud</groupId>    
8
    <artifactId>spring-cloud-starter-config</artifactId>
9
  </dependency>  
10
  <dependency>
11
    <groupId>org.springframework.cloud</groupId>    
12
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>  </dependency> 
13
</dependencies>



application.properties

Properties files
 




xxxxxxxxxx
1


 
1
# application unique name
2
spring.application.name=netflix-eureka-naming-server
3
# it will be the default port which eureka naming server 
4
server.port=8761
5
eureka.client.register-with-eureka=false
6
eureka.client.fetch-registry=false



NetflixEurekaNamingServerApplication.java

  • @EnableEurekaServer annotation will allow the eureka server to control this application.
Java
 




xxxxxxxxxx
1


 
1
@SpringBootApplication
2
@EnableEurekaServer // to enable the communication with Eureka server 
3
public class NetflixEurekaNamingServerApplication { 
4
    public static void main(String[] args) {         SpringApplication.run(NetflixEurekaNamingServerApplication.class, args);     
5
                                           } 
6
} 



After running this application we can access the Eureka server dashboard in the following URL

URL: http://localhost:8761

Eureka Server Dashboard

spring eureka

2) Server Application

  • To perform load distribution, this application needs to run in two instances.
  • spring-cloud-starter-Netflix-eureka-client used to enable communication with Eureka naming server
XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
  <groupId>org.springframework.cloud</groupId>  
3
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
4
</dependency>



pom. xml

XML
 




xxxxxxxxxx
1
13


 
1
<properties>  
2
  <java.version>11</java.version>  
3
  <spring-cloud.version>Hoxton.SR4</spring-cloud.version> 
4
</properties> 
5
<dependencies>  
6
  <dependency>    
7
    <groupId>org.springframework.cloud</groupId>    
8
    <artifactId>spring-cloud-starter-config</artifactId> 
9
  </dependency> 
10
  <dependency>  
11
    <groupId>org.springframework.cloud</groupId>  
12
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>     </dependency>
13
</dependencies>



application. properties

Properties files
 




xxxxxxxxxx
1


 
1
# application unique name 
2
spring.application.name=micro-service-server
3
# application will be running under this port 
4
server.port=4000
5
# end point of load balancing server 
6
eureka.client.service-url.default-zone=http://localhost:8761/eureka



MicroServiceServerApplication.java

  • @EnableDiscoveryClient annotation to register the application with the eureka server.
Java
 


xxxxxxxxxx
1
 
1
@SpringBootApplication
2
@EnableDiscoveryClient
3
public class MicroServiceServerApplication { 
4
    public static void main(String[] args) {         SpringApplication.run(MicroServiceServerApplication.class, args);
5
                                           } 
6
}


ServerController.java

  • It is an ordinary rest controller class
Java
 




xxxxxxxxxx
1
33


 
1
@RestController
2
@RequestMapping("/server")
3
public class ServerController {
4
 
          
5
    @Autowired
6
    private Environment environment;
7
 
          
8
    @GetMapping("/technologyInfo/{platform}")
9
    public ResponseModel retrieveTechnologyInfo(@PathVariable("platform") String platform) {
10
        ResponseModel responseModel = new ResponseModel();
11
 
          
12
        if (platform.equalsIgnoreCase("Java")) {
13
            responseModel.setTittle("Technology Stack");
14
            responseModel.setPlatform("Java");
15
            responseModel.setUsedFor("Secured Web Services");
16
        } else if (platform.equalsIgnoreCase("python")) {
17
            responseModel.setTittle("Technology Stack");
18
            responseModel.setPlatform("python");
19
            responseModel.setUsedFor("Machine Learning");
20
        } else {
21
            responseModel.setTittle("Technology Stack");
22
            responseModel.setPlatform(platform);
23
            responseModel.setUsedFor("Unknown platform");
24
        }
25
 
          
26
        responseModel.setServerPort(Short.parseShort(environment.getProperty("local.server.port")));
27
 
          
28
        return responseModel;
29
 
          
30
    }
31
 
          
32
    ;
33
}



ResponseModel.java

  • It is a traditional model class.
Java
 




xxxxxxxxxx
1


 
1
public class ResponseModel {
2
  private String tittle;
3
  private String platform;
4
  private String usedFor;
5
  private Short serverPort;
6
  /** constructor with getters and setters **/
7
}



Run Server Application Instance in Two Ports

First, simply run the application as a java application using the main method. To run one more instance in another port we need to edit the Run/Debug Configurations In the IDE.

In IntelliJ

Click on the Edit Configuration option, it will be available on the right top side of the menu bar.

edit configurations

It will open a window as follows. Then enable Allow parallel run and press apply.

TestWorkSpace

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 -Server. port=4001 in the VM Arguments as shown in the following images.

run/debug

testapplication

Then select the new configuration and run. Now, these two instances of the server will appear in the eureka server dashboard.

3) Client Application

  • This application will perform as a consumer of APIs which is written in the main server.
  • It consumes the APIs from both main server instances based on availability through the load balancer.
  • We also use the Netflix-eureka-client library to communicate with the 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.
XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
  <groupId>org.springframework.cloud</groupId>
3
  <artifactId>spring-cloud-starter-openfeign</artifactId> 
4
</dependency>



Eureka Client and 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.
XML
 




xxxxxxxxxx
1


 
1
<dependency>  
2
  <groupId>org.springframework.cloud</groupId>  
3
  <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
4
</dependency>
5
<dependency> 
6
  <groupId>org.springframework.cloud</groupId> 
7
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
8
</dependency> 



pom.xml

XML
 




xxxxxxxxxx
1
21


 
1
<properties> 
2
  <java.version>11</java.version> 
3
  <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
4
</properties> 
5
<dependencies> 
6
  <dependency>  
7
    <groupId>org.springframework.cloud</groupId>   
8
    <artifactId>spring-cloud-starter-config</artifactId> 
9
  </dependency> 
10
  <dependency> 
11
    <groupId>org.springframework.cloud</groupId> 
12
    <artifactId>spring-cloud-starter-openfeign</artifactId> 
13
  </dependency> 
14
  <dependency>  
15
    <groupId>org.springframework.cloud</groupId>  
16
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> 
17
  </dependency> 
18
  <dependency>   
19
    <groupId>org.springframework.cloud</groupId>  
20
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>  </dependency>
21
</dependencies>



application.properties

Properties files
 




xxxxxxxxxx
1


 
1
# application unique name 
2
server.servlet.contextPath=/microservice
3
# application will be running under this port 
4
spring.application.name=micro-service-client server.port=5000
5
# end point of load balancing server 
6
eureka.client.service-url.default-zone=http://localhost:8761/eureka 



MicroServiceClientApplication.java

  • @EnableDiscoveryClient annotation used to register the application with the eureka server in the main class.
  • @EnableFeignClients annotation used to connect the feign library.
Java
 




xxxxxxxxxx
1


1
@SpringBootApplication
2
@EnableFeignClients("com.microservices.client") 
3
@EnableDiscoveryClient
4
public class MicroServiceClientApplication {  
5
  public static void main(String[] args) { 
6
    SpringApplication.run(MicroServiceClientApplication.class, args);  
7
                                         } 
8
}



ClientController.java

  • It is an ordinary rest controller class
Java
 




xxxxxxxxxx
1
11


1
@RestController
2
@RequestMapping("/client")
3
public class ClientController {
4
  @Autowired
5
  private ApiProxy apiProxy;
6
  @GetMapping("/technologyInfo/{platform}")
7
  public ResponseModel getTechnologyInfo(@PathVariable("platform") String platform) {
8
    /**API calling using proxy interface and mapping into ResponseModel named Object.**/
9
    ResponseModel responseModel = apiProxy.retrieveTechnologyInfo(platform);
10
    return responseModel;
11
                                                                                    }
12
}



ApiProxy.java

  • Act as a proxy class in between API and client.
  • @FeignClient(name = "micro-service-server") annotation will configure the information of the API exposed application name.
  • @RibbonClient(name = "micro-service-server") annotation will feed the client application with a load-balanced server name.
Java
 




xxxxxxxxxx
1


1
@FeignClient(name = "micro-service-server")
2
@RibbonClient(name = "micro-service-server")
3
public interface ApiProxy {
4
  @GetMapping("/server/technologyInfo/{platform}")
5
  ResponseModel retrieveTechnologyInfo(@PathVariable("platform") String platform);
6
}



ResponseModel.java

  • It is a traditional model class.
Java
 




x





1
public class ResponseModel {
2
  private String tittle;
3
  private String platform;
4
  private String usedFor;
5
  private Short serverPort;
6
  /** constructor with getters and setters **/
7
}



  • After running client application, an instance of this application also appear in the eureka server dashboard.
  • Finally, Eureka Server Dashboard will be as follows.

DS Replicas

Result

  • All client application API to see the load balancing magic.

URI: http://localhost:5000/microservice/client/technologyInfo/java

  • Response:
Java
 




xxxxxxxxxx
1


1
{"tittle":"Technology Stack","platform":"Java","usedFor":"Secured Web Services","serverPort":4000}



  • To refresh:
Java
 




xxxxxxxxxx
1


 
1
{"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. 
Topics:
eureka client, eureka server, java, java web application, load balancer, rest api, sample applications, spring, spring boot, tutorial

Published at DZone with permission of Vishnu Viswambharan . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}