失业在家,学习RMI一例,以做记录。
创建RMI应用程序分四步。自JDK1.5之后不再需要创建存根与基干。
(1)定义和实现远端接口中的参数
(2) 定义和实现远端接口
(3) 编写服务端代码
(4) 编写客户端代码
(5) 启动rmiregistry , 并将服务注册到rmiregistry.
定义和实现远端接口中的参数
这里定义一个学生实体
Code
package rmi;
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
这里student定义为可序列化,这是因为客户端与服务传递参数都是byte stream的形式。然后通过反序列化成对像,才能调用方法。
定义和实现远端接口
1.定义远程接口
Code
package rmi;
import java.rmi.Remote;
public interface InfoConsult extends Remote{
public int getAge(String name);
}
远端接口必须从java.rmi.Remote继承;远端接口中的方法如果要throws异常,这个异常必须是java.rmi.RemoteException(或java.rmi.RemoteException的子类),否则,这个异常就不能被返回到客户端 .
2.实现远程接口
package rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
public class InfoConsultImpl extends UnicastRemoteObject implements InfoConsult{
private List<Student> students;
protected InfoConsultImpl(List<Student> students) throws RemoteException {
super();
this.students = students;
}
private static final long serialVersionUID = -3359466943165065842L;
public int getAge(String name) throws RemoteException{
for(Student stu:students){
if(stu.getName().equals(name)){
return stu.getAge();
}
}
return -1;
}
}
编写服务代码
Code
package rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
public class InfoServer {
public static void main(String args[]) throws RemoteException, MalformedURLException{
InfoServer server = new InfoServer();
InfoConsult consult = new InfoConsultImpl(server.getMockData());
Naming.rebind("rmi://localhost:8888/InfoConsult", consult);
}
public List<Student> getMockData(){
List<Student> lst = new ArrayList<Student>();
lst.add(new Student("guo",26));
lst.add(new Student("zhang",24));
lst.add(new Student("baby",1));
return lst;
}
}
编写客户端代码
Code
package rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class School {
public static void main(String args[]){
try {
InfoConsult consult = (InfoConsult) Naming.lookup("rmi://localhost:8888/InfoConsult");
System.out.println(consult.getAge("baby"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
启动rmiregistry , 并将服务注册到rmiregistry
在服务程序目录下启动rmiregistry 8888或者将classpath设定为服务器程序所在目录。
运行服务端程序,运行客户端程序。可以看到输出1。
这里没有产生存根与基干程序。JDK1.5的RMIC命令默认情况下不再产生基干程序,仅产生存根程序。
那什么时候用到存根程序呢,我做了试验,当服务端有存根程序存在时,而客户端没有存根程序,这里客户端就会报错,说没有找到CLASSNAME_STUB。具体原因还不明,有知道的可留言,谨谢.