Remote Method Invocation 入門

Many examples in this document are adapted from Java: How To Program (3rd Ed.), written by Deitel and Deitel, and Thinking in Java (2nd Edition), written by Bruce Eckel. All examples are solely used for educational purposes. Hopefully, I am not violating any copyright issue here. If so, please do email me.

Please install JDK 1.3.1_02 or later with Java Plugin to view this page. Also, this page is best viewed with browsers (for examples, Mozilla 0.99 or later, IE 6.x or later) with CSS2 support. This document is provided as is. You are welcomed to use it for non-commercial purpose.


Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼

看其他教材


目錄

  1. 前言
  2. Hello World -- RMI
  3. RMI and DB
  4. 查詢 services 清單
  5. RmiJdbc
  6. RMI 的其他議題

前言

Remote Method Invocation (RMI) 類似於之前所說的 RPC (Remote Procedure Call),希望能讓程式開發人員專注於 business logic 而不必分散心思於 networking 以及 marshalling/unmarshalling 的工作。可是已經有了 RPC 為什麼又要 RMI 呢?這是因為 RPC 只支援傳遞一些簡單的資料型態,並無法傳遞 Java 的 object。 另外,由於 RPC 需要定義介面,但是目前各家的介面定義語言 (Interface Definition Language; IDL) 並不相同,造成運作上 的不便。因此 Sun 提出了 RMI 使得程式之間能夠傳遞複雜的資料 型態,而且 IDL 採用的是 Java 標準。

簡單來說,RMI 的運作過程如下:提供 service 的程式先寫好, 然後由 service 的開發者向 registry 註冊。而客戶端需要使用 該服務之前,先向 registry 查詢,然後在取得該服務的參考 (reference) 以後,向 service 提出要求並得到答覆! 有不少的網頁指出,一般來說並不建議使用 IE 來作為載入 RMI applet 的 container。

Hello World -- RMI

在這個範例裡面,我們做一件非常簡單的動作。就是由 service 傳回 "Hello World" 給客戶端,並由客戶端列印出來。而且我們 假設你把 service 安裝在 penguin.im.cyut.edu.tw, 而在你自己使用的電腦上(假設為 Win32 的環境)執行客戶端程式。

RMI and DB

在這個範例中,我們把 service 安裝於 win32 的電腦上,並由該 service 存取 local 的 access 資料庫內的資料,並把資料回傳給位於 Unix 電腦上的 client。

查詢 services 清單

我們可以寫一個小的程式來顯示註冊在某個 server 的所有服務。

RmiJdbc

RmiJdbc 是什麼呢?依據 RmiJdbc 首頁的定義: RmiJdbc is a client/server (Type 3) JDBC Driver that relies on Java RMI. All JDBC classes (like Connection, ResultSet, etc...) are distributed as RMI objects, so that you can distribute as you like the access to any database supporting the JDBC API. In fact, RmiJdbc is just a bridge to allow remote access to JDBC drivers.

首先,我們說明下列程式的關係。

  RMI Client <--> (rmiregistry + RmiJdbc Server) <--> DB Server
在以下的說明中,我們假設 client 是一部 win32 的電腦,rmiregistry 和 RmiJdbc Server 的電腦是 penguin,而資料庫伺服器就是系上的 SQL Server。執行 RMI Client 之前,必須先在 penguin 執行下列步驟:
  1. 需下載 RmiJdbc 以及 MS SQL-2000 的 JDBC Driver,並將這幾個 jar 檔案設定在 CLASSPATH。
  2. 執行 rmiregistry &。注意,由於 rmiregistry 只需要 在一部機器上,因此請先執行 ps -ef | grep rmiregistry 來查看是否 rmiregistry 已經執行。
  3. 執行 RmiJdbc Server:java org.objectweb.rmijdbc.RJJdbcServer -noreg com.microsoft.jdbc.sqlserver.SQLServerDriverNote: the JDBC/ODBC bridge is registered by default, no need to add "sun.jdbc.odbc.JdbcOdbcDriver" to the driver list.
再來就必須開發客戶端的程式。在第一個範例中,我們先說明 application 的使用方式,了解了這種方式以後,你們可以試著把這個範例改成 servlet 的 方式來執行。客戶端的程式是修改 Miguel Angel Llado 的範例。

RMI 的其他議題


Last Updated: Tuesday, 30-Nov-2010 18:20:30 CST
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu