RMI(Remote Method Invocation)系统由以下几个部分组成:
运行过程服务的服务器
需要过程服务的客户端程序
过程服务的接口定义
远程服务的实现
RMI命名服务,使得客户端可以发现远程服务
示例程序:
远程接口:
Task.java
import java.io.Serializable;
public interface Task extends Serializable {
Object execute();
}
Compute.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Compute extends Remote {
Object executeTask(Task t)throws RemoteException;
}
服务器:ComputeEngine.java
import java.rmi.*;
import java.rmi.server.*;
//import compute.*;
public class ComputeEngine extends UnicastRemoteObject implements Compute{
public ComputeEngine() throws RemoteException
{
super();
}
public Object executeTask(Task t)
{
return t.execute();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new RMISecurityManager());
}
String name = "rmi://162.105.146.223/Compute";
try {
Compute engine = new ComputeEngine();
Naming.rebind(name, engine);
System.out.println("ComputeEngine bound");
} catch (Exception e)
{
System.err.println("ComputeEngine exception: "
+ e.getMessage());
e.printStackTrace();
}
}
}
客户端:
Add.java
public class Add implements Task {
//int a,b;
//public Add(int i, int j)
public Add()
{
//this.a = i;
//this.b = j;
}
public Object execute() {
// TODO Auto-generated method stub
return 2;
}
}
ComputeAdd.java
import java.rmi.*;
//import compute.*;
public class ComputeAdd {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new RMISecurityManager());
}
try {
String name = "//162.105.146.223" + "/Compute";
Compute comp = (Compute) Naming.lookup(name);
int a,b;
a = 5;
b = 10;
Add task = new Add();
int result = (Integer) (comp.executeTask(task));
System.out.println(result);
} catch (Exception e) {
System.err.println("ComputeAdd exception: " + e.getMessage());
e.printStackTrace();
}
}
}
运行步骤:
编译接口:
javac compute/Compute.java compute/Task.java
jar cvf compute.jar compute/*.class
将编译好的compute.jar放到apache目录下
编译服务器端:
javac -cp "D:/Program Files/apache2.2/htdocs/classes/compute.jar"
engine/ComputeEngine.java
策略文件:
policy.txt
1.start rmiregistry
2.start java -cp e:/zhangyan/java/compute;"d:/Program Files/apache2.2/htdocs/classes/compute.jar" -Djava.rmi.server.codebase=http://127.0.0.1/classes/compute.jar -Djava.rmi.server.hostname=localhost -Djava.security.policy=server.policy engine.server
3.java -cp e:/zhangyan/java/compute;"d:/Program Files/apache2.2/htdocs/classes/compute.jar" -Djava.rmi.server.codebase=http://127.0.0.1/classes/ -Djava.security.policy=server.policy client.ComputeAdd localhost