看《Head First Design Pattern》的代理模式,先叙述了一个远程代理,用到RMI。
书上的实例是本地部署的,尝试一下在服务器部署RMI。
腾讯云配置:
1核 2GB 1Mbps
系统盘:普通云硬盘
网络:Default-VPC
公网IP:193.112.16.223
目录结构
云端:
客户端:
代码:
云端:
修改GumballMachineTestDrive.java,如下
package proxy.remoteproxy;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class GumballMachineTestDrive {
public static void main(String[] args) {
int count = 0;
GumballMachineRemote gumballMachine = null;
if (args.length < 2) {
System.out.println("GumballMachine <name> <inventory>");
System.exit(1);
}
count = Integer.parseInt(args[1]);
try {
System.setProperty("java.rmi.server.hostname", "193.112.16.223");
gumballMachine = new GumballMachine(args[0], count);
Naming.rebind(args[0], gumballMachine);
System.out.println(" rmi server is ready...");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端:
修改GumballMonitorTestDrive.java,如下
package proxy.remoteproxy;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class GumballMonitorTestDrive {
public static void main(String[] args) {
String[] location = {
"rmi://193.112.16.223/santafe",
"rmi://193.112.16.223/boulder",
"rmi://193.112.16.223/seattle"
};
GumballMonitor[] monitor = new GumballMonitor[location.length];
for (int i = 0; i < location.length; i++) {
try {
GumballMachineRemote machine = (GumballMachineRemote) Naming.lookup(location[i]);
monitor[i] = new GumballMonitor(machine);
System.out.println(monitor[i]);
} catch (RemoteException | MalformedURLException | NotBoundException e) {
e.printStackTrace();
}
}
for (int i = 0; i < monitor.length; i++) {
monitor[i].report();
}
}
}
运行:
1. 云端启动
rmiregistry
java proxy.remoteproxy.GumballMachineTestDrive seattle 350
java proxy.remoteproxy.GumballMachineTestDrive santaft 100
java proxy.remoteproxy.GumballMachineTestDrive boulder 300
2. 客户端启动
结果如图所示,才从客户端获取到云端的信息。