java分布式对象_JAVA基础之分布式对象

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);

}

}

0818b9ca8b590ca3270a3433284dd417.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值