本文共 1694 字,大约阅读时间需要 5 分钟。
RMI编程模型
1)接口与实现import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Warehouse extends Remote {
double getPrice(String description) throws RemoteException;
}/**
* Unicast产生单一对象ip地址和端口
*/
public class WarehouseImpl extends UnicastRemoteObject implements Warehouse {
private Map prices;
protected WarehouseImpl() throws RemoteException {
prices = new HashMap();
prices.put("Blackwell Toaster", 24.95);
prices.put("ZapXpress Microwave Oven", 24.95);
//如果不extends UnicastRemoteObject
//调用静态方法实例化
// UnicastRemoteObject.exportObject(this, 0);
}
@Override
public double getPrice(String description) throws RemoteException {
Double price = prices.get(description);
return price == null ? 0 : price;
}
}
2)RMI注册表public class WarehouseServer {
public static void main(String[] args) throws RemoteException, NamingException {
System.out.println("Constructing server implementiong");
WarehouseImpl warehouse = new WarehouseImpl();
System.out.println("Bingding server implementiong to registry");
Context context = new InitialContext();
context.bind("rmi:warehouse", warehouse);
System.out.println("Waiting for invocations from clients");
}
}public class WarehouseClient {
public static void main(String[] args) throws NamingException, RemoteException {
Context context = new InitialContext();
System.out.println("RMI registry bindings:");
Enumeration e = context.list("rmi://localhost/");
while (e.hasMoreElements()) {
System.out.println(e.nextElement().getName());
}
String url = "rmi://localhost/warehouse";
Warehouse warehouse = (Warehouse) context.lookup(url);
String descr = "Blackwell Toaster";
double price = warehouse.getPrice(url);
System.out.println(descr + ":" + price);
}
}
转载地址:https://blog.csdn.net/weixin_28926205/article/details/114620677 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!