java分布式对象RMI应用测试用例
【0】README
0.1)本文旨在對http://blog.csdn.net/PacosonSWJTU/article/details/50705192? 中的代碼進行實踐(如何部署一個使用RMI框架的程序以進行遠程調用);
0.2) for complete source code, please visit ?https://github.com/pacosonTang/core-java-volume/tree/master/coreJavaAdvanced/chapter11/rmi_test
0.3)目錄結構如下:?
【1】部署前的準備
step1)創建兩個目錄, 分別存放用于啟動server 和 client 的類:
server/ ? ? WarehouseServer.class ? ? Warehouse.class
? ? WarehouseImpl.class
client/ ? ??WarehouseClient.class ? ? Warehouse.class step2)創建download 目錄,用于存放 NanoHTTPD web server?
【1】部署步驟如下
step1)打開一個新的控制臺窗口,轉到download目錄,然后將NanoHTTPD.java(NanoHTTPD web 服務器)復制到這個目錄中。(NanoHTTPD web 服務器的源代碼 ,參見, https://github.com/pacosonTang/core-java-volume/tree/master/coreJavaAdvanced/chapter11/rmi_test)
step2)在server 程序中通過代碼注冊通訊端口和注冊通訊路徑
<span style="font-size:14px;">public class WarehouseServer {public static void main(String[] args){try{WarehouseImpl warehouseService = new WarehouseImpl();// 注冊通訊端口LocateRegistry.createRegistry(1099);// 注冊通訊路徑Naming.rebind("rmi://localhost:1099/warehouseService", warehouseService);System.out.println("warehouse service starts");} catch (Exception e){e.printStackTrace();}} }</span><span style="font-size:14px;">// 這個WarehouseImpl類是遠程方法調用的目標,因為它繼承自UnicastRemoteObject, // 這個類的構造器使得它的對象可供遠程訪問; public class WarehouseImpl extends UnicastRemoteObject implements Warehouse {private Map<String, Double> prices;public WarehouseImpl() throws RemoteException{prices = new HashMap<>();prices.put("A", 24.95);prices.put("B", 49.95);}public double getPrice(String description) throws RemoteException{Double price = prices.get(description);return price == null ? 0 : price;} }</span> <span style="font-size:14px;">// 遠程對象的接口必須擴展Remote接口 public interface Warehouse extends Remote { double getPrice(String description) throws RemoteException; } </span>
step3)現在已經準備好啟動服務器了。打開第三個控制臺窗口,轉到server目錄,并執行下面的命令:
java -Djava.rmi.server.codebase=http://localhost:8080/ WarehouseServer // java.rmi.server.codebase屬性指出了服務類文件的URL。服務器程序將這個URL傳遞給RMI注冊表。
step4)最后,打開第四個控制臺窗口,轉到client目錄,運行:
<span style="font-size:14px;">// 客戶端如何獲得遠程倉庫對象的存根,并調用遠程的getPrice方法。 public class WarehouseClient {public static void main(String[] args){try{Context namingContext = new InitialContext();// NameClassPair是一個助手類: 它包含綁定對象的名字和該對象所屬類的名字。Enumeration<NameClassPair> e = namingContext.list("rmi://localhost:1099/");while (e.hasMoreElements())System.out.println(e.nextElement().getName());// 客戶端可以通過下面的方式,來指定服務器和遠程對象的名字,以此獲得訪問遠程對象所需的存根:String url = "rmi://localhost:1099/warehouseService";Warehouse centralWarehouse = (Warehouse) namingContext.lookup(url);String descr = "A";double price = centralWarehouse.getPrice(descr);System.out.println(descr + ": " + price);} catch (Exception e){e.printStackTrace();}}}</span>
總結
以上是生活随笔為你收集整理的java分布式对象RMI应用测试用例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机qq空间农场在哪里 怎么打开qq农场
- 下一篇: java分布式对象——远程方法中的参数和