Add java implementation for load balancing algorithms

This commit is contained in:
Ashish Pratap Singh
2024-06-01 23:11:42 -07:00
parent 4043fe83f0
commit 180cacd49e
5 changed files with 189 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
import java.util.List;
public class IPHash {
private List<String> servers;
public IPHash(List<String> servers) {
this.servers = servers;
}
public String getNextServer(String clientIp) {
int hash = clientIp.hashCode();
int serverIndex = Math.abs(hash) % servers.size();
return servers.get(serverIndex);
}
public static void main(String[] args) {
List<String> servers = List.of("Server1", "Server2", "Server3");
IPHash ipHash = new IPHash(servers);
List<String> clientIps = List.of("192.168.0.1", "192.168.0.2", "192.168.0.3");
for (String ip : clientIps) {
System.out.println(ip + " is mapped to " + ipHash.getNextServer(ip));
}
}
}