Java RMI和CORBA都是用于分布式計算的技術。
Java RMI(Remote Method Invocation)是Java平臺提供的一種對象間遠程調用技術。Java RMI可以讓分布在不同JVM(Java虛擬機)中的Java對象進行方法調用,就像調用本地對象的方法一樣。
示例代碼: public interface Hello extends Remote { void sayHello() throws RemoteException; } public class HelloImpl extends UnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException {} public void sayHello() throws RemoteException { System.out.println("Hello world!"); } } public class Server { public static void main(String[] args) throws Exception { LocateRegistry.createRegistry(1099); Naming.bind("http://localhost/Hello", new HelloImpl()); System.out.println("Server started."); } } public class Client { public static void main(String[] args) throws Exception { Hello hello = (Hello) Naming.lookup("http://localhost/Hello"); hello.sayHello(); } }
CORBA(Common Object Request Broker Architecture)是一種多語言、多平臺的分布式計算技術。CORBA使用IDL(Interface Definition Language)來定義接口規范,然后使用ORB(Object Request Broker)作為中間件實現方法調用。
示例代碼: interface Hello { void sayHello(); } class HelloImpl extends HelloPOA { public void sayHello() { System.out.println("Hello world!"); } } public class Server { public static void main(String[] args) throws Exception { ORB orb = ORB.init(args, null); POA rootPoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootPoa.the_POAManager().activate(); HelloImpl helloImpl = new HelloImpl(); org.omg.CORBA.Object ref = rootPoa.servant_to_reference(helloImpl); Hello href = HelloHelper.narrow(ref); NamingContextExt ncRef = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService")); NameComponent path[] = { new NameComponent("Hello", "") }; ncRef.rebind(path, href); System.out.println("Server started."); orb.run(); } } public class Client { public static void main(String[] args) throws Exception { ORB orb = ORB.init(args, null); NamingContextExt ncRef = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService")); NameComponent path[] = { new NameComponent("Hello", "") }; Hello hello = HelloHelper.narrow(ncRef.resolve(path)); hello.sayHello(); } }
Java RMI和CORBA的區別是:
- Java RMI只能用于Java語言開發的系統,而CORBA支持多語言。
- Java RMI使用Java高級編程語言作為交互接口,而CORBA使用IDL。
- Java RMI提供了更加簡單和一致的編程模型,而CORBA更加靈活和擴展性強。
- Java RMI使用JVM進行通信,而CORBA使用ORB實例進行通信。