分布式可以大大提高软件的效率,可以将不同的模块分别安装在不同的分机器上,这就对CPU,memory的要求降低了。这就面临不同模块之间的交互,使用RMI就是一个不错的选择(CORBA也可以实现)。
Java RMI 指的是远程方法调用 (Remote Method Invocation)。它是一种机制,它是纯java的能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法。可以用此方法调用的任何对象必须实现该远程接口。
通过下面的例子体会下数据传输的过程。
1:首先定义各一个接口RemoteInterface.java,该接口继承Remote接口,
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteInterface extends Remote {
public String test() throws RemoteException;
}
2:实现上面的接口
import java.io.Serializable;
import java.rmi.RemoteException;
public class RemoteImpl implements RemoteInterface, Serializable {
public String test() throws RemoteException {
return "??>>>>>>>>>>>>>";
}
}
该类就是用于远程调用的对象
3:注册该类到注册服务器中
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class RemoteServer {
public static void main(String[] args) throws RemoteException, MalformedURLException, AlreadyBoundException {
System.err.println("start>>>>>>>>>");
RemoteInterface remoteInterface = new RemoteImpl();
//创建端口号
LocateRegistry.createRegistry(8888);
//在注册服务器上注册该远程对象RemoteInterface
Naming.bind("rmi://10.81.11.39:8888/remoteInterface",remoteInterface);
//为了便于调试,让该线程休息一会
try {
Thread.sleep(3600*3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println("end>>>>>>>>>>>>>");
}
}
然后将RemoteImpl.java, RemoteInterface.java, RemoteServer.java编译的后的class文件放到服务器10.81.11.39上,如果你用本地调试,需要把10.81.11.39改为localhost,同样代码中也要修改。class文件也不需要传到服务器上。
4:运行RemoteServer
java RemoteServer
5:运行RemoteClient.java。 这是后在console上就应该显示??>>>>>>>>>>>>>字样