我有一个RMI CalculatorServer和一个CalculatorClient类。 出于负载平衡的目的,我想知道如何在单独的机器上设置多个服务器,以便多个客户端可以访问任何服务器。
CalculatorServer.java
public class CalculatorServer implements Serializable{
public static void main(String[] args) {
try{
Registry reg = LocateRegistry.createRegistry(7000);
CalculatorImpl ci = new CalculatorImpl();
reg.bind("calc", ci);
JOptionPane.showMessageDialog(null, "Server Started.");
}
catch(RemoteException e){
System.out.println("Server Remote Exception: "+e);
}
catch(AlreadyBoundException e){
System.out.println("Server Already Bound Exception: "+e);
}
}
}
CalculatorClient.java
public class CalculatorClient {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.println("Enter first number :");
int x = sn.nextInt();
System.out.println("Enter second number :");
int y = sn.nextInt();
try{
Registry reg = LocateRegistry.getRegistry("127.0.0.1", 7000);
CalculatorInterface ci = (CalculatorInterface)reg.lookup("calc");
int sum = ci.add(x, y);
System.out.println("Sum is: "+sum);
}
catch(RemoteException e){
System.out.println(" Client Remote Exception: "+e);
}
catch(NotBoundException e){
System.out.println(" Client Remote Exception: "+e);
}
}
}
答案 0 :(得分:0)
假设您有许多服务器(例如5)。您可以使用所有5个IP地址填充arraylist。然后,每次客户端发出请求时,从arraylist中选择一个随机服务器IP。
public class generateServerIP {
public static void main(String args[]){
ArrayList<String> al = new ArrayList<>();
al.add("172.62.22.103");
al.add("172.62.22.123");
al.add("172.62.22.15");
al.add("172.62.22.187");
al.add("172.62.22.110");
int ip = new Random().nextInt(al.size());
System.out.println(al.get(ip));
}
}
要连接服务器,请使用以下命令:
Registry reg = LocateRegistry.getRegistry(ip, 7000);
nextInt(int n)方法使用统一分布,因此从arraylist中选择任何ip的概率等于选择任何其他ip的概率。