参考:
RMI是类似RPC的一种远程方法调用协议,比RPC类型的WebService更简单,也可以跨进程访问
先来创建一个model或者javaBean,注意,该类必须实现序列化Serializable
public class Person implements Serializable {
private int id;
private String name;
private int age;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
调用接口
//此为远程对象调用的接口,必须继承Remote类
public interface PersonService extends Remote {
public List<Person> GetList() throws RemoteException;
}
实现接口,注意必须继承UnicastRemoteObject
public class PersonServiceImpl extends UnicastRemoteObject implements PersonService {
public PersonServiceImpl() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
@Override
public List<Person> GetList() throws RemoteException {
// TODO Auto-generated method stub
System.out.println("Get Person Start!");
List<Person> personList=new LinkedList<Person>();
Person person1=new Person();
person1.setAge(25);
person1.setId(0);
person1.setName("Leslie");
personList.add(person1);
Person person2=new Person();
person2.setAge(25);
person2.setId(1);
person2.setName("Rose");
personList.add(person2);
return personList;
}
}
Server端
public class RMIServer{
public static void main(String[] args)
{
try {
PersonService personService=new PersonServiceImpl();
//注册通讯端口
LocateRegistry.createRegistry(6600);
//注册通讯路径
Naming.rebind("rmi://127.0.0.1:6600/PersonService", personService);
System.out.println("Service Start!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端
public class RMIClient {
public static void main(String[] args){
try{
//调用远程对象,注意RMI路径与接口必须与服务器配置一致
PersonService personService=(PersonService)Naming.lookup("rmi://127.0.0.1:6600/PersonService");
List<Person> personList=personService.GetList();
for(Person person:personList)
{
System.out.println("ID:"+person.getId()+" Age:"+person.getAge()+" Name:"+person.getName());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}