Five load balancing algorithms implemented in Java

Monkey said Java 2021-10-14 06:55:58
load balancing algorithms implemented java


Concept

Load balancing is to access the client request , Forward to each by pre agreed rules server. There are several classical algorithms , Now let's use Java Implement these algorithms .

 picture

Polling algorithm

The polling algorithm assigns each new connection request to the next server in order , Finally, all requests are shared equally among all servers .

advantage : Absolutely fair

shortcoming : Cannot allocate based on server performance , Unable to make rational use of server resources .

package com.monkeyjava.learn.basic.robin;

import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestRound {

private Integer index = 0;
private List<String> ips = Lists.newArrayList("192.168.1.1", "192.168.1.2", "192.168.1.3");


public String roundRobin(){
String serverIp;
synchronized(index){
if (index >= ips.size()){
index = 0;
}
serverIp= ips.get(index);
// polling +1
index ++;
}
return serverIp;
}

public static void main(String[] args) {
TestRound testRoundRobin =new TestRound();
for (int i=0;i< 10 ;i++){
String serverIp= testRoundRobin.roundRobin();
System.out.println(serverIp);
}
}
}

Output results :

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.1

Weighted polling

In this algorithm , The number of connections accepted by each machine is distributed in proportion to the weight . This is an improvement on the ordinary polling algorithm , For example, you can set : The processing capacity of the third machine is twice that of the first machine , Then the load balancer will allocate twice the number of connections to the second 3 Taiwan machine , Polling can assign the request order to the back end according to the weight .

package com.monkeyjava.learn.basic.robin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestWeight {
private Integer index = 0;
static Map<String, Integer> ipMap=new HashMap<String, Integer>(16);
static {
// 1.map, key-ip,value- The weight
ipMap.put("192.168.1.1", 1);
ipMap.put("192.168.1.2", 2);
ipMap.put("192.168.1.3", 4);

}

public List<String> getServerIpByWeight() {
List<String> ips = new ArrayList<String>(32);
for (Map.Entry<String, Integer> entry : ipMap.entrySet()) {
String ip = entry.getKey();
Integer weight = entry.getValue();
// Depending on the weight , Put in list The number in is equal to the weight , The number of times polled is equal to the weight
for (int ipCount =0; ipCount < weight; ipCount++) {
ips.add(ip);
}
}
return ips;
}

public String weightRobin(){
List<String> ips = this.getServerIpByWeight();
if (index >= ips.size()){
index = 0;
}
String serverIp= ips.get(index);
index ++;
return serverIp;
}

public static void main(String[] args) {
TestWeight testWeightRobin=new TestWeight();
for (int i =0;i< 10 ;i++){
String server=testWeightRobin.weightRobin();
System.out.println(server);
}
}
}

Output results :

192.168.1.1
192.168.1.3
192.168.1.3
192.168.1.3
192.168.1.3
192.168.1.2
192.168.1.2
192.168.1.1
192.168.1.3
192.168.1.3

Weighted random method

Get random numbers with weights , Random this kind of thing , Can't see absolutely , Only relative , We don't have to index Control subscripts for polling , Only random Random sampling ip, Implementation algorithm .

package com.monkeyjava.learn.basic.robin;

import java.util.*;

public class TestRandomWeight {

static Map<String, Integer> ipMap=new HashMap<String, Integer>(16);
static {
// 1.map, key-ip,value- The weight
ipMap.put("192.168.1.1", 1);
ipMap.put("192.168.1.2", 2);
ipMap.put("192.168.1.3", 4);

}

public List<String> getServerIpByWeight() {
List<String> ips = new ArrayList<String>(32);
for (Map.Entry<String, Integer> entry : ipMap.entrySet()) {
String ip = entry.getKey();
Integer weight = entry.getValue();
// Depending on the weight , Put in list The number in is equal to the weight , The number of times polled is equal to the weight
for (int ipCount =0; ipCount < weight; ipCount++) {
ips.add(ip);
}
}
return ips;
}

public String randomWeightRobin(){
List<String> ips = this.getServerIpByWeight();
// Cyclic random number
Random random=new Random();
int index =random.nextInt(ips.size());
String serverIp = ips.get(index);
return serverIp;
}

public static void main(String[] args) {
TestRandomWeight testRandomWeightRobin=new TestRandomWeight();
for (int i =0;i< 10 ;i++){
String server= testRandomWeightRobin.randomWeightRobin();
System.out.println(server);
}
}
}

Output results :

192.168.1.3
192.168.1.3
192.168.1.2
192.168.1.1
192.168.1.2
192.168.1.1
192.168.1.3
192.168.1.2
192.168.1.2
192.168.1.3

Random method

The load balancing method randomly distributes the load to each available server , Select a server through the random number generation algorithm , This implementation algorithm is the simplest , The number of calls increases , This algorithm can achieve that the number of requests per server is close to the average .

package com.monkeyjava.learn.basic.robin;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Random;

public class TestRandom {


private List<String> ips = Lists.newArrayList("192.168.1.1", "192.168.1.2", "192.168.1.3");


public String randomRobin(){
// random number
Random random=new Random();
int index =random.nextInt(ips.size());
String serverIp= ips.get(index);
return serverIp;

}

public static void main(String[] args) {
TestRandom testRandomdRobin =new TestRandom();
for (int i=0;i< 10 ;i++){
String serverIp= testRandomdRobin.randomRobin();
System.out.println(serverIp);
}
}
}

Output

192.168.1.3
192.168.1.3
192.168.1.1
192.168.1.2
192.168.1.1
192.168.1.3
192.168.1.2
192.168.1.3
192.168.1.3
192.168.1.2

IP_Hash Algorithm

hash(ip)%N Algorithm , Through a hashing algorithm, the client source IP The request is allocated to different servers according to the hash modulus algorithm

advantage : The same client is guaranteed IP The address will be hashed to the same back-end server , Until the back-end server list changes . According to this feature, stateful communication can be established between service consumers and service providers session conversation

shortcoming : If the server goes offline , Source IP Routing server IP Will become another , If the server does not do session Shared words , Can cause session The loss of .

package com.monkeyjava.learn.basic.robin;

import com.google.common.collect.Lists;

import java.util.List;

public class TestIpHash {


private List<String> ips = Lists.newArrayList("192.168.1.1", "192.168.1.2", "192.168.1.3");


public String ipHashRobin(String clientIp){
int hashCode=clientIp.hashCode();
int serverListsize=ips.size();
int index = hashCode%serverListsize;
String serverIp= ips.get(index);
return serverIp;

}

public static void main(String[] args) {
TestIpHash testIpHash =new TestIpHash();
String servername= testIpHash.ipHashRobin("192.168.88.2");
System.out.println(servername);
}
}

Output results

192.168.1.3

The result is the same every time

 Brother monkey said Java
Brother monkey said Java
An Internet coder ,Java Technology enthusiasts , Like to share
12 Original content
official account


版权声明
本文为[Monkey said Java]所创,转载请带上原文链接,感谢
https://javamana.com/2021/10/20211002145640985d.html

  1. Hadoop Foundation - 03 - hdfs (Hadoop Distributed File System) Basic Concepts
  2. Hadoop Foundation - 05 - hdfs Project (word Frequency Statistics)
  3. Hadoop Foundation - 06 - hdfs Data Read and write
  4. The "monthly test" report card of the new car built under the lack of core: Xiaopeng and Weilai took the lead in "breaking 10000", and the ideal plummeted by 25%
  5. Introduction to making arch linux software package
  6. Hard core observation 407 HTTPS everywhere browser extension is about to retire
  7. How to use busybox on Linux
  8. In 2021, the talent incentive plan of Linux foundation open source software School Park was officially launched
  9. It's not windows or Linux. Shrink is the "God operating system"
  10. Install anydesk on Ubuntu Linux
  11. 2021, can we recommend using Linux to play games?
  12. not exist:org.springframework.kafka.listener.AbstractMessageListenerContaingetContainerProperties()
  13. Are you sure HTTPS is asymmetric encryption for content encryption? See the answers and reasons
  14. MySQL online slow log query
  15. Java JDK server installation
  16. 手把手教你使用Java开发在线生成pdf文档
  17. Questions d'entrevue dans la base de données MySQL (dernière version 2021)
  18. Java零基础小白入门必做题汇总(建议收藏)第一篇
  19. Day15 Java Foundation
  20. Day16 Java Foundation
  21. Day17 Java Foundation
  22. Day18 Java Foundation
  23. Linux installe JDK 1.8 et configure les variables d'environnement
  24. Tutoriel d'utilisation Maven super détaillé
  25. Spring boot reads project parameter configuration
  26. Docker installing rocketmq
  27. Java Zero Basic small white Beginner must make a summary of issues (recommended Collection) Chapitre 1
  28. Manuel pour vous apprendre à utiliser le développement Java pour générer des documents PDF en ligne
  29. 40 + comment les femmes s'habillent - elles pour montrer leur jeunesse?Un manteau et une jupe vous donnent un look haut de gamme tout au long de l'automne et de l'hiver
  30. Tutoriel d'installation Ubuntu 16.04 / Hadoop 3.1.3Configuration autonome / pseudo - distribuée
  31. L'apprentissage le plus détaillé de springboot à l'échelle du réseau - day01
  32. L'apprentissage le plus détaillé de springboot sur le Web - day02
  33. L'apprentissage le plus détaillé de springboot sur le Web - day03
  34. L'apprentissage le plus détaillé de springboot sur le Web - day04
  35. Tutoriel d'utilisation Maven super détaillé
  36. L'apprentissage le plus détaillé de springboot sur le Web - day05
  37. L'apprentissage le plus détaillé de springboot sur le Web - day06
  38. L'apprentissage le plus détaillé de springboot sur le Web - day07
  39. Introduction to JavaScript - write a photo album for your girlfriend
  40. [Hadoop 3. X] HDFS storage type and storage strategy (V) overview
  41. L'apprentissage le plus détaillé de springboot sur le Web - day08
  42. Introduction à la page Web de rabbitmq (3)
  43. No Converter found for return value of type: class java.util.arraylist Error Problem
  44. (16) , spring cloud stream message driven
  45. Que faut - il apprendre de l'architecture des microservices Spring Cloud?
  46. Résolution: erreur: Java: distribution cible invalide: 11problème d'erreur
  47. Springboot démarre en une minute et sort de l'enfer de la configuration SSM!
  48. Maven - un outil de gestion essentiel pour les grands projets d'usine, de l'introduction à la maîtrise![️ Collection recommandée]
  49. ️ Push to interview in Large Factory ᥧ - - Spring Boot Automatic Assembly Principle
  50. [️ springboot Template Engine] - thymeleaf
  51. Springboot - MVC Automatic configuration Principle
  52. Mybatis reverse engineering and the use of new version mybatisplus 3.4 reverse engineering
  53. Base de données MySQL - transactions et index
  54. Sécurité du printemps - [authentification, autorisation, déconnexion et contrôle des droits]
  55. Moteur de base de données InnoDB diffère de myisam
  56. Swagger - [springboot Integrated Swagger, configure Swagger, configure scan Interface, configure API Group]
  57. Cadre de sécurité Shiro - [QUICKstart, login Block, User Authentication, request Authorization]
  58. [Introduction à Java] installation de l'environnement de développement - Introduction à Java et construction de l'environnement
  59. 【 linux】 notes d'utilisation tmux
  60. MySQL + mybatis paging query - database series learning notes